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

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

        const employee_documents = await db.employee_documents.create(
            {
                id: data.id || undefined,
        
        documentType: data.documentType
        ||
        null
            ,
            
        fileName: data.fileName
        ||
        null
            ,
            
        uploadedAt: data.uploadedAt
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employee_documents.setEmployee( data.employee || null, {
            transaction,
        });
        
        await employee_documents.setUploadedByUser( data.uploadedByUser || null, {
            transaction,
        });
        

        

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

        return employee_documents;
    }
    

    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 employee_documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                documentType: item.documentType
            ||
            null
            ,
            
                fileName: item.fileName
            ||
            null
            ,
            
                uploadedAt: item.uploadedAt
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return employee_documents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.documentType !== undefined) updatePayload.documentType = data.documentType;
        
        
        if (data.fileName !== undefined) updatePayload.fileName = data.fileName;
        
        
        if (data.uploadedAt !== undefined) updatePayload.uploadedAt = data.uploadedAt;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await employee_documents.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.uploadedByUser !== undefined) {
            await employee_documents.setUploadedByUser(
              
              data.uploadedByUser,
              
              { transaction }
            );
        }
        

        
        

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

        return employee_documents;
    }

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

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

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


        return employee_documents;
    }

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

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

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

        await employee_documents.destroy({
            transaction
        });

        return employee_documents;
    }

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

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

        if (!employee_documents) {
            return employee_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await employee_documents.getEmployee({
            transaction
        });
        
        
        output.filePath = await employee_documents.getFilePath({
            transaction
        });
        
        
        output.uploadedByUser = await employee_documents.getUploadedByUser({
            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.employees,
        as: 'employee',
        
        where: filter.employee ? {
          [Op.or]: [
            { id: { [Op.in]: filter.employee.split('|').map(term => Utils.uuid(term)) } },
            {
              employeeCode: {
                [Op.or]: filter.employee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'uploadedByUser',
        
        where: filter.uploadedByUser ? {
          [Op.or]: [
            { id: { [Op.in]: filter.uploadedByUser.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.uploadedByUser.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

            
            

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

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

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

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

            
            if (filter.documentType) {
                where = {
                    ...where,
                documentType: filter.documentType,
            };
            }
            


      

      



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

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

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

    
};

