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

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

        const sales = await db.sales.create(
            {
                id: data.id || undefined,
        
        receipt_number: data.receipt_number
        ||
        null
            ,
            
        sale_type: data.sale_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        sold_at: data.sold_at
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        discount_total: data.discount_total
        ||
        null
            ,
            
        tax_total: data.tax_total
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        amount_paid: data.amount_paid
        ||
        null
            ,
            
        change_due: data.change_due
        ||
        null
            ,
            
        void_reason: data.void_reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sales.setBranch( data.branch || null, {
            transaction,
        });
        
        await sales.setRegister( data.register || null, {
            transaction,
        });
        
        await sales.setShift( data.shift || null, {
            transaction,
        });
        
        await sales.setCashier( data.cashier || null, {
            transaction,
        });
        
        await sales.setCustomer( data.customer || null, {
            transaction,
        });
        
        await sales.setDiscount_approved_by( data.discount_approved_by || null, {
            transaction,
        });
        
        await sales.setVoided_by( data.voided_by || null, {
            transaction,
        });
        
        await sales.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return sales;
    }
    

    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 salesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                receipt_number: item.receipt_number
            ||
            null
            ,
            
                sale_type: item.sale_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                sold_at: item.sold_at
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                discount_total: item.discount_total
            ||
            null
            ,
            
                tax_total: item.tax_total
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                amount_paid: item.amount_paid
            ||
            null
            ,
            
                change_due: item.change_due
            ||
            null
            ,
            
                void_reason: item.void_reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return sales;
    }

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

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


        

        const updatePayload = {};
        
        if (data.receipt_number !== undefined) updatePayload.receipt_number = data.receipt_number;
        
        
        if (data.sale_type !== undefined) updatePayload.sale_type = data.sale_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.sold_at !== undefined) updatePayload.sold_at = data.sold_at;
        
        
        if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
        
        
        if (data.discount_total !== undefined) updatePayload.discount_total = data.discount_total;
        
        
        if (data.tax_total !== undefined) updatePayload.tax_total = data.tax_total;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.amount_paid !== undefined) updatePayload.amount_paid = data.amount_paid;
        
        
        if (data.change_due !== undefined) updatePayload.change_due = data.change_due;
        
        
        if (data.void_reason !== undefined) updatePayload.void_reason = data.void_reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.branch !== undefined) {
            await sales.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.register !== undefined) {
            await sales.setRegister(
              
              data.register,
              
              { transaction }
            );
        }
        
        if (data.shift !== undefined) {
            await sales.setShift(
              
              data.shift,
              
              { transaction }
            );
        }
        
        if (data.cashier !== undefined) {
            await sales.setCashier(
              
              data.cashier,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await sales.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.discount_approved_by !== undefined) {
            await sales.setDiscount_approved_by(
              
              data.discount_approved_by,
              
              { transaction }
            );
        }
        
        if (data.voided_by !== undefined) {
            await sales.setVoided_by(
              
              data.voided_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await sales.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return sales;
    }

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

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

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


        return sales;
    }

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

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

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

        await sales.destroy({
            transaction
        });

        return sales;
    }

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

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

        if (!sales) {
            return sales;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sale_lines_sale = await sales.getSale_lines_sale({
            transaction
        });
        
        
        output.payments_sale = await sales.getPayments_sale({
            transaction
        });
        
        
        output.refunds_sale = await sales.getRefunds_sale({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.branch = await sales.getBranch({
            transaction
        });
        
        
        output.register = await sales.getRegister({
            transaction
        });
        
        
        output.shift = await sales.getShift({
            transaction
        });
        
        
        output.cashier = await sales.getCashier({
            transaction
        });
        
        
        output.customer = await sales.getCustomer({
            transaction
        });
        
        
        output.discount_approved_by = await sales.getDiscount_approved_by({
            transaction
        });
        
        
        output.voided_by = await sales.getVoided_by({
            transaction
        });
        
        
        output.organizations = await sales.getOrganizations({
            transaction
        });
        
        

        return output;
    }

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

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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

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

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

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.receipt_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales',
                        'receipt_number',
                        filter.receipt_number,
                    ),
                };
            }
            
            if (filter.void_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales',
                        'void_reason',
                        filter.void_reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

      

      

      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.sales.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

