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

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

        const jobs = await db.jobs.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        budget_min: data.budget_min
        ||
        null
            ,
            
        budget_max: data.budget_max
        ||
        null
            ,
            
        budget_type: data.budget_type
        ||
        null
            ,
            
        deadline_at: data.deadline_at
        ||
        null
            ,
            
        posted_at: data.posted_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        is_remote: data.is_remote
        ||
        false
        
            ,
            
        location_requirement: data.location_requirement
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await jobs.setClient( data.client || null, {
            transaction,
        });
        
        await jobs.setCategory( data.category || null, {
            transaction,
        });
        

        
        await jobs.setRequired_skills(data.required_skills || [], {
            transaction,
        });
        
        await jobs.setAttachments(data.attachments || [], {
            transaction,
        });
        

        

        return jobs;
    }
    

    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 jobsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                budget_min: item.budget_min
            ||
            null
            ,
            
                budget_max: item.budget_max
            ||
            null
            ,
            
                budget_type: item.budget_type
            ||
            null
            ,
            
                deadline_at: item.deadline_at
            ||
            null
            ,
            
                posted_at: item.posted_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                is_remote: item.is_remote
            ||
            false
        
            ,
            
                location_requirement: item.location_requirement
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return jobs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.budget_min !== undefined) updatePayload.budget_min = data.budget_min;
        
        
        if (data.budget_max !== undefined) updatePayload.budget_max = data.budget_max;
        
        
        if (data.budget_type !== undefined) updatePayload.budget_type = data.budget_type;
        
        
        if (data.deadline_at !== undefined) updatePayload.deadline_at = data.deadline_at;
        
        
        if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.is_remote !== undefined) updatePayload.is_remote = data.is_remote;
        
        
        if (data.location_requirement !== undefined) updatePayload.location_requirement = data.location_requirement;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.client !== undefined) {
            await jobs.setClient(
              
              data.client,
              
              { transaction }
            );
        }
        
        if (data.category !== undefined) {
            await jobs.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        

        
        
        if (data.required_skills !== undefined) {
            await jobs.setRequired_skills(data.required_skills, { transaction });
        }
        
        if (data.attachments !== undefined) {
            await jobs.setAttachments(data.attachments, { transaction });
        }
        

        

        return jobs;
    }

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

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

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


        return jobs;
    }

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

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

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

        await jobs.destroy({
            transaction
        });

        return jobs;
    }

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

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

        if (!jobs) {
            return jobs;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.job_attachments_job = await jobs.getJob_attachments_job({
            transaction
        });
        
        
        output.proposals_job = await jobs.getProposals_job({
            transaction
        });
        
        
        output.contracts_job = await jobs.getContracts_job({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.client = await jobs.getClient({
            transaction
        });
        
        
        output.category = await jobs.getCategory({
            transaction
        });
        
        
        output.required_skills = await jobs.getRequired_skills({
            transaction
        });
        
        
        output.attachments = await jobs.getAttachments({
            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.users,
        as: 'client',
        
        where: filter.client ? {
          [Op.or]: [
            { id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.skills,
        as: 'required_skills',
        required: false,
      },

      {
        model: db.job_attachments,
        as: 'attachments',
        required: false,
      },


    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'jobs',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'jobs',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.location_requirement) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'jobs',
                        'location_requirement',
                        filter.location_requirement,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    deadline_at: {
                    ...where.deadline_at,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.budget_type) {
                where = {
                    ...where,
                budget_type: filter.budget_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.is_remote) {
                where = {
                    ...where,
                is_remote: filter.is_remote,
            };
            }
            


      

      


      if (filter.required_skills) {
        const searchTerms = filter.required_skills.split('|');

        include = [
          {
            model: db.skills,
            as: 'required_skills_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.attachments) {
        const searchTerms = filter.attachments.split('|');

        include = [
          {
            model: db.job_attachments,
            as: 'attachments_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  caption: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

