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

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

        const applicants = await db.applicants.create(
            {
                id: data.id || undefined,
        
        applicationDate: data.applicationDate
        ||
        null
            ,
            
        firstName: data.firstName
        ||
        null
            ,
            
        lastName: data.lastName
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        mobile: data.mobile
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
        interviewSchedule: data.interviewSchedule
        ||
        null
            ,
            
        interviewResult: data.interviewResult
        ||
        null
            ,
            
        psychTestResult: data.psychTestResult
        ||
        null
            ,
            
        medicalResult: data.medicalResult
        ||
        null
            ,
            
        backgroundCheck: data.backgroundCheck
        ||
        null
            ,
            
        jobOfferStatus: data.jobOfferStatus
        ||
        null
            ,
            
        expectedStartDate: data.expectedStartDate
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await applicants.setJobRequisition( data.jobRequisition || null, {
            transaction,
        });
        
        await applicants.setConvertedEmployee( data.convertedEmployee || null, {
            transaction,
        });
        

        

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

        return applicants;
    }
    

    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 applicantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                applicationDate: item.applicationDate
            ||
            null
            ,
            
                firstName: item.firstName
            ||
            null
            ,
            
                lastName: item.lastName
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                mobile: item.mobile
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
                interviewSchedule: item.interviewSchedule
            ||
            null
            ,
            
                interviewResult: item.interviewResult
            ||
            null
            ,
            
                psychTestResult: item.psychTestResult
            ||
            null
            ,
            
                medicalResult: item.medicalResult
            ||
            null
            ,
            
                backgroundCheck: item.backgroundCheck
            ||
            null
            ,
            
                jobOfferStatus: item.jobOfferStatus
            ||
            null
            ,
            
                expectedStartDate: item.expectedStartDate
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return applicants;
    }

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

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


        

        const updatePayload = {};
        
        if (data.applicationDate !== undefined) updatePayload.applicationDate = data.applicationDate;
        
        
        if (data.firstName !== undefined) updatePayload.firstName = data.firstName;
        
        
        if (data.lastName !== undefined) updatePayload.lastName = data.lastName;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.mobile !== undefined) updatePayload.mobile = data.mobile;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.interviewSchedule !== undefined) updatePayload.interviewSchedule = data.interviewSchedule;
        
        
        if (data.interviewResult !== undefined) updatePayload.interviewResult = data.interviewResult;
        
        
        if (data.psychTestResult !== undefined) updatePayload.psychTestResult = data.psychTestResult;
        
        
        if (data.medicalResult !== undefined) updatePayload.medicalResult = data.medicalResult;
        
        
        if (data.backgroundCheck !== undefined) updatePayload.backgroundCheck = data.backgroundCheck;
        
        
        if (data.jobOfferStatus !== undefined) updatePayload.jobOfferStatus = data.jobOfferStatus;
        
        
        if (data.expectedStartDate !== undefined) updatePayload.expectedStartDate = data.expectedStartDate;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.jobRequisition !== undefined) {
            await applicants.setJobRequisition(
              
              data.jobRequisition,
              
              { transaction }
            );
        }
        
        if (data.convertedEmployee !== undefined) {
            await applicants.setConvertedEmployee(
              
              data.convertedEmployee,
              
              { transaction }
            );
        }
        

        
        

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

        return applicants;
    }

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

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

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


        return applicants;
    }

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

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

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

        await applicants.destroy({
            transaction
        });

        return applicants;
    }

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

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

        if (!applicants) {
            return applicants;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.jobRequisition = await applicants.getJobRequisition({
            transaction
        });
        
        
        output.resumeFile = await applicants.getResumeFile({
            transaction
        });
        
        
        output.convertedEmployee = await applicants.getConvertedEmployee({
            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.job_requisitions,
        as: 'jobRequisition',
        
        where: filter.jobRequisition ? {
          [Op.or]: [
            { id: { [Op.in]: filter.jobRequisition.split('|').map(term => Utils.uuid(term)) } },
            {
              positionTitle: {
                [Op.or]: filter.jobRequisition.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.firstName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'applicants',
                        'firstName',
                        filter.firstName,
                    ),
                };
            }
            
            if (filter.lastName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'applicants',
                        'lastName',
                        filter.lastName,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'applicants',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.mobile) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'applicants',
                        'mobile',
                        filter.mobile,
                    ),
                };
            }
            
            if (filter.psychTestResult) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'applicants',
                        'psychTestResult',
                        filter.psychTestResult,
                    ),
                };
            }
            
            if (filter.medicalResult) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'applicants',
                        'medicalResult',
                        filter.medicalResult,
                    ),
                };
            }
            
            if (filter.backgroundCheck) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'applicants',
                        'backgroundCheck',
                        filter.backgroundCheck,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.source) {
                where = {
                    ...where,
                source: filter.source,
            };
            }
            
            if (filter.interviewResult) {
                where = {
                    ...where,
                interviewResult: filter.interviewResult,
            };
            }
            
            if (filter.jobOfferStatus) {
                where = {
                    ...where,
                jobOfferStatus: filter.jobOfferStatus,
            };
            }
            


      

      



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

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

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

    
};

