
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_method: data.payment_method
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        paid_at: data.paid_at
        ||
        null
            ,
            
        provider_reference: data.provider_reference
        ||
        null
            ,
            
        receipt_text: data.receipt_text
        ||
        null
            ,
            
        points_earned: data.points_earned
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payments.setRestaurant( data.restaurant || null, {
            transaction,
        });
        
        await payments.setOrder( data.order || null, {
            transaction,
        });
        
        await payments.setClient_user( data.client_user || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payments.getTableName(),
                belongsToColumn: 'receipt_file',
                belongsToId: payments.id,
            },
            data.receipt_file,
            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_method: item.payment_method
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                paid_at: item.paid_at
            ||
            null
            ,
            
                provider_reference: item.provider_reference
            ||
            null
            ,
            
                receipt_text: item.receipt_text
            ||
            null
            ,
            
                points_earned: item.points_earned
            ||
            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: 'receipt_file',
                    belongsToId: payments[i].id,
                },
                data[i].receipt_file,
                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_method !== undefined) updatePayload.payment_method = data.payment_method;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
        
        
        if (data.provider_reference !== undefined) updatePayload.provider_reference = data.provider_reference;
        
        
        if (data.receipt_text !== undefined) updatePayload.receipt_text = data.receipt_text;
        
        
        if (data.points_earned !== undefined) updatePayload.points_earned = data.points_earned;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payments.getTableName(),
                belongsToColumn: 'receipt_file',
                belongsToId: payments.id,
            },
            data.receipt_file,
            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.loyalty_transactions_payment = await payments.getLoyalty_transactions_payment({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.restaurant = await payments.getRestaurant({
            transaction
        });
        
        
        output.order = await payments.getOrder({
            transaction
        });
        
        
        output.client_user = await payments.getClient_user({
            transaction
        });
        
        
        output.receipt_file = await payments.getReceipt_file({
            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.restaurants,
        as: 'restaurant',
        
        where: filter.restaurant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.restaurant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.restaurant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

        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.receipt_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payments',
                        'receipt_text',
                        filter.receipt_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.payment_method) {
                where = {
                    ...where,
                payment_method: filter.payment_method,
            };
            }
            
            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,
        }));
    }

    
};

