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

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

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

        
        await pos_shifts.setBranch( data.branch || null, {
            transaction,
        });
        
        await pos_shifts.setRegister( data.register || null, {
            transaction,
        });
        
        await pos_shifts.setCashier( data.cashier || null, {
            transaction,
        });
        
        await pos_shifts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return pos_shifts;
    }
    

    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 pos_shiftsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                shift_number: item.shift_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                opened_at: item.opened_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
                opening_cash: item.opening_cash
            ||
            null
            ,
            
                closing_cash_counted: item.closing_cash_counted
            ||
            null
            ,
            
                expected_cash: item.expected_cash
            ||
            null
            ,
            
                cash_difference: item.cash_difference
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return pos_shifts;
    }

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


        

        const updatePayload = {};
        
        if (data.shift_number !== undefined) updatePayload.shift_number = data.shift_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        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_cash !== undefined) updatePayload.opening_cash = data.opening_cash;
        
        
        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;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.branch !== undefined) {
            await pos_shifts.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.register !== undefined) {
            await pos_shifts.setRegister(
              
              data.register,
              
              { transaction }
            );
        }
        
        if (data.cashier !== undefined) {
            await pos_shifts.setCashier(
              
              data.cashier,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await pos_shifts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return pos_shifts;
    }

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

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

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


        return pos_shifts;
    }

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

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

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

        await pos_shifts.destroy({
            transaction
        });

        return pos_shifts;
    }

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

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

        if (!pos_shifts) {
            return pos_shifts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sales_shift = await pos_shifts.getSales_shift({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.branch = await pos_shifts.getBranch({
            transaction
        });
        
        
        output.register = await pos_shifts.getRegister({
            transaction
        });
        
        
        output.cashier = await pos_shifts.getCashier({
            transaction
        });
        
        
        output.organizations = await pos_shifts.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.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.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

    
};

