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

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

        const cash_registers = await db.cash_registers.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        cash_drawer_balance: data.cash_drawer_balance
        ||
        null
            ,
            
        pix_enabled: data.pix_enabled
        ||
        false
        
            ,
            
        credit_enabled: data.credit_enabled
        ||
        false
        
            ,
            
        debit_enabled: data.debit_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cash_registers.setStore( data.store || null, {
            transaction,
        });
        

        

        

        return cash_registers;
    }
    

    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 cash_registersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                cash_drawer_balance: item.cash_drawer_balance
            ||
            null
            ,
            
                pix_enabled: item.pix_enabled
            ||
            false
        
            ,
            
                credit_enabled: item.credit_enabled
            ||
            false
        
            ,
            
                debit_enabled: item.debit_enabled
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return cash_registers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.cash_drawer_balance !== undefined) updatePayload.cash_drawer_balance = data.cash_drawer_balance;
        
        
        if (data.pix_enabled !== undefined) updatePayload.pix_enabled = data.pix_enabled;
        
        
        if (data.credit_enabled !== undefined) updatePayload.credit_enabled = data.credit_enabled;
        
        
        if (data.debit_enabled !== undefined) updatePayload.debit_enabled = data.debit_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.store !== undefined) {
            await cash_registers.setStore(
              
              data.store,
              
              { transaction }
            );
        }
        

        
        

        

        return cash_registers;
    }

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

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

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


        return cash_registers;
    }

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

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

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

        await cash_registers.destroy({
            transaction
        });

        return cash_registers;
    }

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

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

        if (!cash_registers) {
            return cash_registers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sales_transactions_register = await cash_registers.getSales_transactions_register({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.store = await cash_registers.getStore({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'cash_registers',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    cash_drawer_balance: {
                    ...where.cash_drawer_balance,
                            [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.pix_enabled) {
                where = {
                    ...where,
                pix_enabled: filter.pix_enabled,
            };
            }
            
            if (filter.credit_enabled) {
                where = {
                    ...where,
                credit_enabled: filter.credit_enabled,
            };
            }
            
            if (filter.debit_enabled) {
                where = {
                    ...where,
                debit_enabled: filter.debit_enabled,
            };
            }
            


      



            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.cash_registers.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(
                        'cash_registers',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

