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

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

        const sales_transactions = await db.sales_transactions.create(
            {
                id: data.id || undefined,
        
        sold_at: data.sold_at
        ||
        null
            ,
            
        payment_method: data.payment_method
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        subtotal_amount: data.subtotal_amount
        ||
        null
            ,
            
        tax_amount: data.tax_amount
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sales_transactions.setStore( data.store || null, {
            transaction,
        });
        
        await sales_transactions.setRegister( data.register || null, {
            transaction,
        });
        
        await sales_transactions.setCashier_employee( data.cashier_employee || null, {
            transaction,
        });
        
        await sales_transactions.setCustomer_npc( data.customer_npc || null, {
            transaction,
        });
        

        

        

        return sales_transactions;
    }
    

    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 sales_transactionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sold_at: item.sold_at
            ||
            null
            ,
            
                payment_method: item.payment_method
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                subtotal_amount: item.subtotal_amount
            ||
            null
            ,
            
                tax_amount: item.tax_amount
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return sales_transactions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.sold_at !== undefined) updatePayload.sold_at = data.sold_at;
        
        
        if (data.payment_method !== undefined) updatePayload.payment_method = data.payment_method;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
        
        
        if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.store !== undefined) {
            await sales_transactions.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        
        if (data.register !== undefined) {
            await sales_transactions.setRegister(
              
              data.register,
              
              { transaction }
            );
        }
        
        if (data.cashier_employee !== undefined) {
            await sales_transactions.setCashier_employee(
              
              data.cashier_employee,
              
              { transaction }
            );
        }
        
        if (data.customer_npc !== undefined) {
            await sales_transactions.setCustomer_npc(
              
              data.customer_npc,
              
              { transaction }
            );
        }
        

        
        

        

        return sales_transactions;
    }

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

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

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


        return sales_transactions;
    }

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

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

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

        await sales_transactions.destroy({
            transaction
        });

        return sales_transactions;
    }

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

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

        if (!sales_transactions) {
            return sales_transactions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sales_transaction_lines_sales_transaction = await sales_transactions.getSales_transaction_lines_sales_transaction({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store = await sales_transactions.getStore({
            transaction
        });
        
        
        output.register = await sales_transactions.getRegister({
            transaction
        });
        
        
        output.cashier_employee = await sales_transactions.getCashier_employee({
            transaction
        });
        
        
        output.customer_npc = await sales_transactions.getCustomer_npc({
            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.market_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.cash_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.employees,
        as: 'cashier_employee',
        
        where: filter.cashier_employee ? {
          [Op.or]: [
            { id: { [Op.in]: filter.cashier_employee.split('|').map(term => Utils.uuid(term)) } },
            {
              job_title: {
                [Op.or]: filter.cashier_employee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            sold_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    sold_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    tax_amount: {
                    ...where.tax_amount,
                            [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.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.sales_transactions.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(
                        'sales_transactions',
                        'status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

