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

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

        const shifts = await db.shifts.create(
            {
                id: data.id || undefined,
        
        opened_at: data.opened_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
        opening_cash_amount: data.opening_cash_amount
        ||
        null
            ,
            
        closing_cash_amount: data.closing_cash_amount
        ||
        null
            ,
            
        expected_cash_amount: data.expected_cash_amount
        ||
        null
            ,
            
        cash_variance_amount: data.cash_variance_amount
        ||
        null
            ,
            
        shift_status: data.shift_status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return 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 shiftsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                opened_at: item.opened_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
                opening_cash_amount: item.opening_cash_amount
            ||
            null
            ,
            
                closing_cash_amount: item.closing_cash_amount
            ||
            null
            ,
            
                expected_cash_amount: item.expected_cash_amount
            ||
            null
            ,
            
                cash_variance_amount: item.cash_variance_amount
            ||
            null
            ,
            
                shift_status: item.shift_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 shifts = await db.shifts.bulkCreate(shiftsData, { transaction });

        // For each item created, replace relation files
        

        return 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 shifts = await db.shifts.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_cash_amount !== undefined) updatePayload.opening_cash_amount = data.opening_cash_amount;
        
        
        if (data.closing_cash_amount !== undefined) updatePayload.closing_cash_amount = data.closing_cash_amount;
        
        
        if (data.expected_cash_amount !== undefined) updatePayload.expected_cash_amount = data.expected_cash_amount;
        
        
        if (data.cash_variance_amount !== undefined) updatePayload.cash_variance_amount = data.cash_variance_amount;
        
        
        if (data.shift_status !== undefined) updatePayload.shift_status = data.shift_status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return shifts;
    }

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

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

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


        return shifts;
    }

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

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

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

        await shifts.destroy({
            transaction
        });

        return shifts;
    }

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

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

        if (!shifts) {
            return shifts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.carts_shift = await shifts.getCarts_shift({
            transaction
        });
        
        
        
        output.orders_shift = await shifts.getOrders_shift({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.register = await shifts.getRegister({
            transaction
        });
        
        
        output.opened_by_user = await shifts.getOpened_by_user({
            transaction
        });
        
        
        output.closed_by_user = await shifts.getClosed_by_user({
            transaction
        });
        
        
        output.organizations = await 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.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: '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(
                        'shifts',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.shift_status) {
                where = {
                    ...where,
                shift_status: filter.shift_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.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(
                        'shifts',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

