
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class TransactionsDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const transactions = await db.transactions.create(
            {
                id: data.id || undefined,
        
        transaction_type: data.transaction_type
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency_code: data.currency_code
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        provider_name: data.provider_name
        ||
        null
            ,
            
        provider_reference: data.provider_reference
        ||
        null
            ,
            
        initiated_at: data.initiated_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await transactions.setUser( data.user || null, {
            transaction,
        });
        
        await transactions.setPost( data.post || null, {
            transaction,
        });
        
        await transactions.setEvent( data.event || null, {
            transaction,
        });
        
        await transactions.setTicket( data.ticket || null, {
            transaction,
        });
        

        

        

        return transactions;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const transactionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                transaction_type: item.transaction_type
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency_code: item.currency_code
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                provider_name: item.provider_name
            ||
            null
            ,
            
                provider_reference: item.provider_reference
            ||
            null
            ,
            
                initiated_at: item.initiated_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const transactions = await db.transactions.bulkCreate(transactionsData, { transaction });

        // For each item created, replace relation files
        

        return transactions;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const transactions = await db.transactions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.transaction_type !== undefined) updatePayload.transaction_type = data.transaction_type;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.provider_name !== undefined) updatePayload.provider_name = data.provider_name;
        
        
        if (data.provider_reference !== undefined) updatePayload.provider_reference = data.provider_reference;
        
        
        if (data.initiated_at !== undefined) updatePayload.initiated_at = data.initiated_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        updatePayload.updatedById = currentUser.id;

        await transactions.update(updatePayload, {transaction});

        
        
        if (data.user !== undefined) {
            await transactions.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.post !== undefined) {
            await transactions.setPost(
              
              data.post,
              
              { transaction }
            );
        }
        
        if (data.event !== undefined) {
            await transactions.setEvent(
              
              data.event,
              
              { transaction }
            );
        }
        
        if (data.ticket !== undefined) {
            await transactions.setTicket(
              
              data.ticket,
              
              { transaction }
            );
        }
        

        
        

        

        return transactions;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const transactions = await db.transactions.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of transactions) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of transactions) {
                await record.destroy({transaction});
            }
        });


        return transactions;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const transactions = await db.transactions.findByPk(id, options);

        await transactions.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await transactions.destroy({
            transaction
        });

        return transactions;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const transactions = await db.transactions.findOne(
            { where },
            { transaction },
        );

        if (!transactions) {
            return transactions;
        }

        const output = transactions.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await transactions.getUser({
            transaction
        });
        
        
        output.post = await transactions.getPost({
            transaction
        });
        
        
        output.event = await transactions.getEvent({
            transaction
        });
        
        
        output.ticket = await transactions.getTicket({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.posts,
        as: 'post',
        
        where: filter.post ? {
          [Op.or]: [
            { id: { [Op.in]: filter.post.split('|').map(term => Utils.uuid(term)) } },
            {
              caption: {
                [Op.or]: filter.post.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.events,
        as: 'event',
        
        where: filter.event ? {
          [Op.or]: [
            { id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
            {
              title_text: {
                [Op.or]: filter.event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.tickets,
        as: 'ticket',
        
        where: filter.ticket ? {
          [Op.or]: [
            { id: { [Op.in]: filter.ticket.split('|').map(term => Utils.uuid(term)) } },
            {
              ticket_code: {
                [Op.or]: filter.ticket.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.provider_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transactions',
                        'provider_name',
                        filter.provider_name,
                    ),
                };
            }
            
            if (filter.provider_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transactions',
                        'provider_reference',
                        filter.provider_reference,
                    ),
                };
            }
            

            
            

            
            if (filter.amountRange) {
                const [start, end] = filter.amountRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    amount: {
                    ...where.amount,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    amount: {
                    ...where.amount,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.initiated_atRange) {
                const [start, end] = filter.initiated_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    initiated_at: {
                    ...where.initiated_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    initiated_at: {
                    ...where.initiated_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.completed_atRange) {
                const [start, end] = filter.completed_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    completed_at: {
                    ...where.completed_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    completed_at: {
                    ...where.completed_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.transaction_type) {
                where = {
                    ...where,
                transaction_type: filter.transaction_type,
            };
            }
            
            if (filter.currency_code) {
                where = {
                    ...where,
                currency_code: filter.currency_code,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

      

      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.transactions.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'transactions',
                        'provider_reference',
                        query,
                    ),
                ],
            };
        }

        const records = await db.transactions.findAll({
            attributes: [ 'id', 'provider_reference' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['provider_reference', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.provider_reference,
        }));
    }

    
};

