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

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

        const career_coach_reports = await db.career_coach_reports.create(
            {
                id: data.id || undefined,
        
        resume_text: data.resume_text
        ||
        null
            ,
            
        current_role_text: data.current_role_text
        ||
        null
            ,
            
        target_role_text: data.target_role_text
        ||
        null
            ,
            
        clarifying_questions: data.clarifying_questions
        ||
        null
            ,
            
        career_path: data.career_path
        ||
        null
            ,
            
        skill_gaps: data.skill_gaps
        ||
        null
            ,
            
        next_steps: data.next_steps
        ||
        null
            ,
            
        resume_suggestions: data.resume_suggestions
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        share_token: data.share_token
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await career_coach_reports.setUser( data.user || null, {
            transaction,
        });
        
        await career_coach_reports.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return career_coach_reports;
    }
    

    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 career_coach_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                resume_text: item.resume_text
            ||
            null
            ,
            
                current_role_text: item.current_role_text
            ||
            null
            ,
            
                target_role_text: item.target_role_text
            ||
            null
            ,
            
                clarifying_questions: item.clarifying_questions
            ||
            null
            ,
            
                career_path: item.career_path
            ||
            null
            ,
            
                skill_gaps: item.skill_gaps
            ||
            null
            ,
            
                next_steps: item.next_steps
            ||
            null
            ,
            
                resume_suggestions: item.resume_suggestions
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                share_token: item.share_token
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return career_coach_reports;
    }

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


        

        const updatePayload = {};
        
        if (data.resume_text !== undefined) updatePayload.resume_text = data.resume_text;
        
        
        if (data.current_role_text !== undefined) updatePayload.current_role_text = data.current_role_text;
        
        
        if (data.target_role_text !== undefined) updatePayload.target_role_text = data.target_role_text;
        
        
        if (data.clarifying_questions !== undefined) updatePayload.clarifying_questions = data.clarifying_questions;
        
        
        if (data.career_path !== undefined) updatePayload.career_path = data.career_path;
        
        
        if (data.skill_gaps !== undefined) updatePayload.skill_gaps = data.skill_gaps;
        
        
        if (data.next_steps !== undefined) updatePayload.next_steps = data.next_steps;
        
        
        if (data.resume_suggestions !== undefined) updatePayload.resume_suggestions = data.resume_suggestions;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.share_token !== undefined) updatePayload.share_token = data.share_token;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await career_coach_reports.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await career_coach_reports.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return career_coach_reports;
    }

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

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

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


        return career_coach_reports;
    }

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

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

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

        await career_coach_reports.destroy({
            transaction
        });

        return career_coach_reports;
    }

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

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

        if (!career_coach_reports) {
            return career_coach_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await career_coach_reports.getUser({
            transaction
        });
        
        
        output.resume_file = await career_coach_reports.getResume_file({
            transaction
        });
        
        
        output.organizations = await career_coach_reports.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: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.resume_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'career_coach_reports',
                        'resume_text',
                        filter.resume_text,
                    ),
                };
            }
            
            if (filter.current_role_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'career_coach_reports',
                        'current_role_text',
                        filter.current_role_text,
                    ),
                };
            }
            
            if (filter.target_role_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'career_coach_reports',
                        'target_role_text',
                        filter.target_role_text,
                    ),
                };
            }
            
            if (filter.clarifying_questions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'career_coach_reports',
                        'clarifying_questions',
                        filter.clarifying_questions,
                    ),
                };
            }
            
            if (filter.career_path) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'career_coach_reports',
                        'career_path',
                        filter.career_path,
                    ),
                };
            }
            
            if (filter.skill_gaps) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'career_coach_reports',
                        'skill_gaps',
                        filter.skill_gaps,
                    ),
                };
            }
            
            if (filter.next_steps) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'career_coach_reports',
                        'next_steps',
                        filter.next_steps,
                    ),
                };
            }
            
            if (filter.resume_suggestions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'career_coach_reports',
                        'resume_suggestions',
                        filter.resume_suggestions,
                    ),
                };
            }
            
            if (filter.share_token) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'career_coach_reports',
                        'share_token',
                        filter.share_token,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

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

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

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

    
};

