
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
            ,
            
        sold_at: data.sold_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        subtotal: data.subtotal
        ||
        null
            ,
            
        discount_total: data.discount_total
        ||
        null
            ,
            
        vat_total: data.vat_total
        ||
        null
            ,
            
        grand_total: data.grand_total
        ||
        null
            ,
            
        amount_paid: data.amount_paid
        ||
        null
            ,
            
        change_given: data.change_given
        ||
        null
            ,
            
        receipt_delivery: data.receipt_delivery
        ||
        null
            ,
            
        customer_email: data.customer_email
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sales.setStore( data.store || null, {
            transaction,
        });
        
        await sales.setRegister( data.register || null, {
            transaction,
        });
        
        await sales.setCashier( data.cashier || null, {
            transaction,
        });
        
        await sales.setCustomer( data.customer || null, {
            transaction,
        });
        
        await sales.setCash_drawer_session( data.cash_drawer_session || 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
            ,
            
                sold_at: item.sold_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                subtotal: item.subtotal
            ||
            null
            ,
            
                discount_total: item.discount_total
            ||
            null
            ,
            
                vat_total: item.vat_total
            ||
            null
            ,
            
                grand_total: item.grand_total
            ||
            null
            ,
            
                amount_paid: item.amount_paid
            ||
            null
            ,
            
                change_given: item.change_given
            ||
            null
            ,
            
                receipt_delivery: item.receipt_delivery
            ||
            null
            ,
            
                customer_email: item.customer_email
            ||
            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 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.sold_at !== undefined) updatePayload.sold_at = data.sold_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
        
        
        if (data.discount_total !== undefined) updatePayload.discount_total = data.discount_total;
        
        
        if (data.vat_total !== undefined) updatePayload.vat_total = data.vat_total;
        
        
        if (data.grand_total !== undefined) updatePayload.grand_total = data.grand_total;
        
        
        if (data.amount_paid !== undefined) updatePayload.amount_paid = data.amount_paid;
        
        
        if (data.change_given !== undefined) updatePayload.change_given = data.change_given;
        
        
        if (data.receipt_delivery !== undefined) updatePayload.receipt_delivery = data.receipt_delivery;
        
        
        if (data.customer_email !== undefined) updatePayload.customer_email = data.customer_email;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.store !== undefined) {
            await sales.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        
        if (data.register !== undefined) {
            await sales.setRegister(
              
              data.register,
              
              { transaction }
            );
        }
        
        if (data.cashier !== undefined) {
            await sales.setCashier(
              
              data.cashier,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await sales.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.cash_drawer_session !== undefined) {
            await sales.setCash_drawer_session(
              
              data.cash_drawer_session,
              
              { 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_items_sale = await sales.getSale_items_sale({
            transaction
        });
        
        
        output.payments_sale = await sales.getPayments_sale({
            transaction
        });
        
        
        output.returns_original_sale = await sales.getReturns_original_sale({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.store = await sales.getStore({
            transaction
        });
        
        
        output.register = await sales.getRegister({
            transaction
        });
        
        
        output.cashier = await sales.getCashier({
            transaction
        });
        
        
        output.customer = await sales.getCustomer({
            transaction
        });
        
        
        output.cash_drawer_session = await sales.getCash_drawer_session({
            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.stores,
        as: 'store',
        
        where: filter.store ? {
          [Op.or]: [
            { id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.registers,
        as: 'register',
        
        where: filter.register ? {
          [Op.or]: [
            { id: { [Op.in]: filter.register.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.register.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)) } },
            {
              full_name: {
                [Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.cash_drawer_sessions,
        as: 'cash_drawer_session',
        
        where: filter.cash_drawer_session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.cash_drawer_session.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.cash_drawer_session.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.customer_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales',
                        'customer_email',
                        filter.customer_email,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sales',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    grand_total: {
                    ...where.grand_total,
                            [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_givenRange) {
                const [start, end] = filter.change_givenRange;

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

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

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

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


      

      

      

      

      

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

    
};

