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

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

        const cash_drawer_sessions = await db.cash_drawer_sessions.create(
            {
                id: data.id || undefined,
        
        opened_at: data.opened_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
        opening_float: data.opening_float
        ||
        null
            ,
            
        closing_cash_counted: data.closing_cash_counted
        ||
        null
            ,
            
        expected_cash: data.expected_cash
        ||
        null
            ,
            
        cash_difference: data.cash_difference
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await cash_drawer_sessions.setRegister( data.register || null, {
            transaction,
        });
        
        await cash_drawer_sessions.setOpened_by_user( data.opened_by_user || null, {
            transaction,
        });
        
        await cash_drawer_sessions.setClosed_by_user( data.closed_by_user || null, {
            transaction,
        });
        
        await cash_drawer_sessions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return cash_drawer_sessions;
    }
    

    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_drawer_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                opened_at: item.opened_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
                opening_float: item.opening_float
            ||
            null
            ,
            
                closing_cash_counted: item.closing_cash_counted
            ||
            null
            ,
            
                expected_cash: item.expected_cash
            ||
            null
            ,
            
                cash_difference: item.cash_difference
            ||
            null
            ,
            
                status: item.status
            ||
            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 cash_drawer_sessions = await db.cash_drawer_sessions.bulkCreate(cash_drawer_sessionsData, { transaction });

        // For each item created, replace relation files
        

        return cash_drawer_sessions;
    }

    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 cash_drawer_sessions = await db.cash_drawer_sessions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        if (data.opening_float !== undefined) updatePayload.opening_float = data.opening_float;
        
        
        if (data.closing_cash_counted !== undefined) updatePayload.closing_cash_counted = data.closing_cash_counted;
        
        
        if (data.expected_cash !== undefined) updatePayload.expected_cash = data.expected_cash;
        
        
        if (data.cash_difference !== undefined) updatePayload.cash_difference = data.cash_difference;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.register !== undefined) {
            await cash_drawer_sessions.setRegister(
              
              data.register,
              
              { transaction }
            );
        }
        
        if (data.opened_by_user !== undefined) {
            await cash_drawer_sessions.setOpened_by_user(
              
              data.opened_by_user,
              
              { transaction }
            );
        }
        
        if (data.closed_by_user !== undefined) {
            await cash_drawer_sessions.setClosed_by_user(
              
              data.closed_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await cash_drawer_sessions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return cash_drawer_sessions;
    }

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

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

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


        return cash_drawer_sessions;
    }

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

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

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

        await cash_drawer_sessions.destroy({
            transaction
        });

        return cash_drawer_sessions;
    }

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

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

        if (!cash_drawer_sessions) {
            return cash_drawer_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sales_cash_drawer_session = await cash_drawer_sessions.getSales_cash_drawer_session({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.register = await cash_drawer_sessions.getRegister({
            transaction
        });
        
        
        output.opened_by_user = await cash_drawer_sessions.getOpened_by_user({
            transaction
        });
        
        
        output.closed_by_user = await cash_drawer_sessions.getClosed_by_user({
            transaction
        });
        
        
        output.organizations = await cash_drawer_sessions.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.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: 'opened_by_user',
        
        where: filter.opened_by_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.opened_by_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.opened_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

        const records = await db.cash_drawer_sessions.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,
        }));
    }

    
};

