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

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

        const job_companies = await db.job_companies.create(
            {
                id: data.id || undefined,
        
        company_name: data.company_name
        ||
        null
            ,
            
        company_legal_name: data.company_legal_name
        ||
        null
            ,
            
        company_website: data.company_website
        ||
        null
            ,
            
        company_size: data.company_size
        ||
        null
            ,
            
        verification_status: data.verification_status
        ||
        null
            ,
            
        about: data.about
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await job_companies.setOwner( data.owner || null, {
            transaction,
        });
        
        await job_companies.setHq_address( data.hq_address || null, {
            transaction,
        });
        
        await job_companies.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return job_companies;
    }
    

    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_companiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                company_name: item.company_name
            ||
            null
            ,
            
                company_legal_name: item.company_legal_name
            ||
            null
            ,
            
                company_website: item.company_website
            ||
            null
            ,
            
                company_size: item.company_size
            ||
            null
            ,
            
                verification_status: item.verification_status
            ||
            null
            ,
            
                about: item.about
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return job_companies;
    }

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


        

        const updatePayload = {};
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        if (data.company_legal_name !== undefined) updatePayload.company_legal_name = data.company_legal_name;
        
        
        if (data.company_website !== undefined) updatePayload.company_website = data.company_website;
        
        
        if (data.company_size !== undefined) updatePayload.company_size = data.company_size;
        
        
        if (data.verification_status !== undefined) updatePayload.verification_status = data.verification_status;
        
        
        if (data.about !== undefined) updatePayload.about = data.about;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await job_companies.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.hq_address !== undefined) {
            await job_companies.setHq_address(
              
              data.hq_address,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await job_companies.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return job_companies;
    }

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

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

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


        return job_companies;
    }

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

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

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

        await job_companies.destroy({
            transaction
        });

        return job_companies;
    }

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

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

        if (!job_companies) {
            return job_companies;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.job_listings_company = await job_companies.getJob_listings_company({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner = await job_companies.getOwner({
            transaction
        });
        
        
        output.company_images = await job_companies.getCompany_images({
            transaction
        });
        
        
        output.hq_address = await job_companies.getHq_address({
            transaction
        });
        
        
        output.organizations = await job_companies.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.users,
        as: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'job_companies',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.company_legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'job_companies',
                        'company_legal_name',
                        filter.company_legal_name,
                    ),
                };
            }
            
            if (filter.company_website) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'job_companies',
                        'company_website',
                        filter.company_website,
                    ),
                };
            }
            
            if (filter.about) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'job_companies',
                        'about',
                        filter.about,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.company_size) {
                where = {
                    ...where,
                company_size: filter.company_size,
            };
            }
            
            if (filter.verification_status) {
                where = {
                    ...where,
                verification_status: filter.verification_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_companies.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_companies',
                        'company_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

