
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 PaymentsDBApi {
    

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

        const payments = await db.payments.create(
            {
                id: data.id || undefined,
        
        payment_type: data.payment_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        reference_code: data.reference_code
        ||
        null
            ,
            
        provider_transaction_code: data.provider_transaction_code
        ||
        null
            ,
            
        initiated_at: data.initiated_at
        ||
        null
            ,
            
        confirmed_at: data.confirmed_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payments.setRepair_order( data.repair_order || null, {
            transaction,
        });
        
        await payments.setPayment_method( data.payment_method || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payments.getTableName(),
                belongsToColumn: 'proof_files',
                belongsToId: payments.id,
            },
            data.proof_files,
            options,
        );
        

        return payments;
    }
    

    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 paymentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                payment_type: item.payment_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                reference_code: item.reference_code
            ||
            null
            ,
            
                provider_transaction_code: item.provider_transaction_code
            ||
            null
            ,
            
                initiated_at: item.initiated_at
            ||
            null
            ,
            
                confirmed_at: item.confirmed_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < payments.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.payments.getTableName(),
                    belongsToColumn: 'proof_files',
                    belongsToId: payments[i].id,
                },
                data[i].proof_files,
                options,
            );
        }
        

        return payments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.payment_type !== undefined) updatePayload.payment_type = data.payment_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.reference_code !== undefined) updatePayload.reference_code = data.reference_code;
        
        
        if (data.provider_transaction_code !== undefined) updatePayload.provider_transaction_code = data.provider_transaction_code;
        
        
        if (data.initiated_at !== undefined) updatePayload.initiated_at = data.initiated_at;
        
        
        if (data.confirmed_at !== undefined) updatePayload.confirmed_at = data.confirmed_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.repair_order !== undefined) {
            await payments.setRepair_order(
              
              data.repair_order,
              
              { transaction }
            );
        }
        
        if (data.payment_method !== undefined) {
            await payments.setPayment_method(
              
              data.payment_method,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payments.getTableName(),
                belongsToColumn: 'proof_files',
                belongsToId: payments.id,
            },
            data.proof_files,
            options,
        );
        

        return payments;
    }

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

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

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


        return payments;
    }

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

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

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

        await payments.destroy({
            transaction
        });

        return payments;
    }

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

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

        if (!payments) {
            return payments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.repair_order = await payments.getRepair_order({
            transaction
        });
        
        
        output.payment_method = await payments.getPayment_method({
            transaction
        });
        
        
        output.proof_files = await payments.getProof_files({
            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.repair_orders,
        as: 'repair_order',
        
        where: filter.repair_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.repair_order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.repair_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'proof_files',
      },

    ];

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

            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payments',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.reference_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payments',
                        'reference_code',
                        filter.reference_code,
                    ),
                };
            }
            
            if (filter.provider_transaction_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payments',
                        'provider_transaction_code',
                        filter.provider_transaction_code,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payments',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.confirmed_atRange) {
                const [start, end] = filter.confirmed_atRange;

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

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

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

            
            if (filter.payment_type) {
                where = {
                    ...where,
                payment_type: filter.payment_type,
            };
            }
            
            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.payments.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(
                        'payments',
                        'reference_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

