
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,
        
        provider: data.provider
        ||
        null
            ,
            
        provider_reference: data.provider_reference
        ||
        null
            ,
            
        checkout_url: data.checkout_url
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency_code: data.currency_code
        ||
        null
            ,
            
        initiated_at: data.initiated_at
        ||
        null
            ,
            
        confirmed_at: data.confirmed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payments.setOrder( data.order || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payments.getTableName(),
                belongsToColumn: 'raw_payload_files',
                belongsToId: payments.id,
            },
            data.raw_payload_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,
                
                provider: item.provider
            ||
            null
            ,
            
                provider_reference: item.provider_reference
            ||
            null
            ,
            
                checkout_url: item.checkout_url
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency_code: item.currency_code
            ||
            null
            ,
            
                initiated_at: item.initiated_at
            ||
            null
            ,
            
                confirmed_at: item.confirmed_at
            ||
            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: 'raw_payload_files',
                    belongsToId: payments[i].id,
                },
                data[i].raw_payload_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.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.provider_reference !== undefined) updatePayload.provider_reference = data.provider_reference;
        
        
        if (data.checkout_url !== undefined) updatePayload.checkout_url = data.checkout_url;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
        
        
        if (data.initiated_at !== undefined) updatePayload.initiated_at = data.initiated_at;
        
        
        if (data.confirmed_at !== undefined) updatePayload.confirmed_at = data.confirmed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.order !== undefined) {
            await payments.setOrder(
              
              data.order,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payments.getTableName(),
                belongsToColumn: 'raw_payload_files',
                belongsToId: payments.id,
            },
            data.raw_payload_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.payment_events_payment = await payments.getPayment_events_payment({
            transaction
        });
        
        
        output.refunds_payment = await payments.getRefunds_payment({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.order = await payments.getOrder({
            transaction
        });
        
        
        output.raw_payload_files = await payments.getRaw_payload_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.orders,
        as: 'order',
        
        where: filter.order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

            
            

            
            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.provider) {
                where = {
                    ...where,
                provider: filter.provider,
            };
            }
            
            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',
                        'provider_reference',
                        query,
                    ),
                ],
            };
        }

        const records = await db.payments.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,
        }));
    }

    
};

