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

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

        const job_listings = await db.job_listings.create(
            {
                id: data.id || undefined,
        
        job_title: data.job_title
        ||
        null
            ,
            
        employment_type: data.employment_type
        ||
        null
            ,
            
        work_mode: data.work_mode
        ||
        null
            ,
            
        location_text: data.location_text
        ||
        null
            ,
            
        salary_min: data.salary_min
        ||
        null
            ,
            
        salary_max: data.salary_max
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        posted_at: data.posted_at
        ||
        null
            ,
            
        closes_at: data.closes_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await job_listings.setCompany( data.company || null, {
            transaction,
        });
        
        await job_listings.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return job_listings;
    }
    

    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 job_listingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                job_title: item.job_title
            ||
            null
            ,
            
                employment_type: item.employment_type
            ||
            null
            ,
            
                work_mode: item.work_mode
            ||
            null
            ,
            
                location_text: item.location_text
            ||
            null
            ,
            
                salary_min: item.salary_min
            ||
            null
            ,
            
                salary_max: item.salary_max
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                posted_at: item.posted_at
            ||
            null
            ,
            
                closes_at: item.closes_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return job_listings;
    }

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


        

        const updatePayload = {};
        
        if (data.job_title !== undefined) updatePayload.job_title = data.job_title;
        
        
        if (data.employment_type !== undefined) updatePayload.employment_type = data.employment_type;
        
        
        if (data.work_mode !== undefined) updatePayload.work_mode = data.work_mode;
        
        
        if (data.location_text !== undefined) updatePayload.location_text = data.location_text;
        
        
        if (data.salary_min !== undefined) updatePayload.salary_min = data.salary_min;
        
        
        if (data.salary_max !== undefined) updatePayload.salary_max = data.salary_max;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
        
        
        if (data.closes_at !== undefined) updatePayload.closes_at = data.closes_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await job_listings.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await job_listings.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return job_listings;
    }

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

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

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


        return job_listings;
    }

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

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

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

        await job_listings.destroy({
            transaction
        });

        return job_listings;
    }

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

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

        if (!job_listings) {
            return job_listings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.job_applications_job_listing = await job_listings.getJob_applications_job_listing({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await job_listings.getCompany({
            transaction
        });
        
        
        output.organizations = await job_listings.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.job_companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              company_name: {
                [Op.or]: filter.company.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.job_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'job_listings',
                        'job_title',
                        filter.job_title,
                    ),
                };
            }
            
            if (filter.location_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'job_listings',
                        'location_text',
                        filter.location_text,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'job_listings',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.employment_type) {
                where = {
                    ...where,
                employment_type: filter.employment_type,
            };
            }
            
            if (filter.work_mode) {
                where = {
                    ...where,
                work_mode: filter.work_mode,
            };
            }
            
            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.job_listings.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(
                        'job_listings',
                        'job_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

