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

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

        const payslips = await db.payslips.create(
            {
                id: data.id || undefined,
        
        slip_number: data.slip_number
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        delivery_status: data.delivery_status
        ||
        null
            ,
            
        sent_at: data.sent_at
        ||
        null
            ,
            
        delivery_notes: data.delivery_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await payslips.setPayroll_item( data.payroll_item || null, {
            transaction,
        });
        
        await payslips.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payslips.getTableName(),
                belongsToColumn: 'pdf_file',
                belongsToId: payslips.id,
            },
            data.pdf_file,
            options,
        );
        

        return payslips;
    }
    

    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 payslipsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                slip_number: item.slip_number
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                delivery_status: item.delivery_status
            ||
            null
            ,
            
                sent_at: item.sent_at
            ||
            null
            ,
            
                delivery_notes: item.delivery_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < payslips.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.payslips.getTableName(),
                    belongsToColumn: 'pdf_file',
                    belongsToId: payslips[i].id,
                },
                data[i].pdf_file,
                options,
            );
        }
        

        return payslips;
    }

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


        

        const updatePayload = {};
        
        if (data.slip_number !== undefined) updatePayload.slip_number = data.slip_number;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.delivery_status !== undefined) updatePayload.delivery_status = data.delivery_status;
        
        
        if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
        
        
        if (data.delivery_notes !== undefined) updatePayload.delivery_notes = data.delivery_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.payroll_item !== undefined) {
            await payslips.setPayroll_item(
              
              data.payroll_item,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await payslips.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.payslips.getTableName(),
                belongsToColumn: 'pdf_file',
                belongsToId: payslips.id,
            },
            data.pdf_file,
            options,
        );
        

        return payslips;
    }

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

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

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


        return payslips;
    }

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

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

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

        await payslips.destroy({
            transaction
        });

        return payslips;
    }

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

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

        if (!payslips) {
            return payslips;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payroll_item = await payslips.getPayroll_item({
            transaction
        });
        
        
        output.pdf_file = await payslips.getPdf_file({
            transaction
        });
        
        
        output.organizations = await payslips.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.payroll_items,
        as: 'payroll_item',
        
        where: filter.payroll_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payroll_item.split('|').map(term => Utils.uuid(term)) } },
            {
              adjustment_notes: {
                [Op.or]: filter.payroll_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'pdf_file',
      },

    ];

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

            
            if (filter.slip_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payslips',
                        'slip_number',
                        filter.slip_number,
                    ),
                };
            }
            
            if (filter.delivery_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'payslips',
                        'delivery_notes',
                        filter.delivery_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.delivery_status) {
                where = {
                    ...where,
                delivery_status: filter.delivery_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.payslips.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(
                        'payslips',
                        'slip_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

