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

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

        const private_profiles = await db.private_profiles.create(
            {
                id: data.id || undefined,
        
        primary_role: data.primary_role
        ||
        null
            ,
            
        goals_summary: data.goals_summary
        ||
        null
            ,
            
        focus_area: data.focus_area
        ||
        null
            ,
            
        time_commitment: data.time_commitment
        ||
        null
            ,
            
        constraints_notes: data.constraints_notes
        ||
        null
            ,
            
        ai_profile_draft: data.ai_profile_draft
        ||
        null
            ,
            
        vision_statement: data.vision_statement
        ||
        null
            ,
            
        onboarding_completed_at: data.onboarding_completed_at
        ||
        null
            ,
            
        linked_accounts_intent: data.linked_accounts_intent
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await private_profiles.setUser( data.user || null, {
            transaction,
        });
        

        
        await private_profiles.setResume_documents(data.resume_documents || [], {
            transaction,
        });
        
        await private_profiles.setCoaching_sessions(data.coaching_sessions || [], {
            transaction,
        });
        

        

        return private_profiles;
    }
    

    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 private_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                primary_role: item.primary_role
            ||
            null
            ,
            
                goals_summary: item.goals_summary
            ||
            null
            ,
            
                focus_area: item.focus_area
            ||
            null
            ,
            
                time_commitment: item.time_commitment
            ||
            null
            ,
            
                constraints_notes: item.constraints_notes
            ||
            null
            ,
            
                ai_profile_draft: item.ai_profile_draft
            ||
            null
            ,
            
                vision_statement: item.vision_statement
            ||
            null
            ,
            
                onboarding_completed_at: item.onboarding_completed_at
            ||
            null
            ,
            
                linked_accounts_intent: item.linked_accounts_intent
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return private_profiles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.primary_role !== undefined) updatePayload.primary_role = data.primary_role;
        
        
        if (data.goals_summary !== undefined) updatePayload.goals_summary = data.goals_summary;
        
        
        if (data.focus_area !== undefined) updatePayload.focus_area = data.focus_area;
        
        
        if (data.time_commitment !== undefined) updatePayload.time_commitment = data.time_commitment;
        
        
        if (data.constraints_notes !== undefined) updatePayload.constraints_notes = data.constraints_notes;
        
        
        if (data.ai_profile_draft !== undefined) updatePayload.ai_profile_draft = data.ai_profile_draft;
        
        
        if (data.vision_statement !== undefined) updatePayload.vision_statement = data.vision_statement;
        
        
        if (data.onboarding_completed_at !== undefined) updatePayload.onboarding_completed_at = data.onboarding_completed_at;
        
        
        if (data.linked_accounts_intent !== undefined) updatePayload.linked_accounts_intent = data.linked_accounts_intent;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        
        if (data.resume_documents !== undefined) {
            await private_profiles.setResume_documents(data.resume_documents, { transaction });
        }
        
        if (data.coaching_sessions !== undefined) {
            await private_profiles.setCoaching_sessions(data.coaching_sessions, { transaction });
        }
        

        

        return private_profiles;
    }

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

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

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


        return private_profiles;
    }

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

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

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

        await private_profiles.destroy({
            transaction
        });

        return private_profiles;
    }

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

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

        if (!private_profiles) {
            return private_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await private_profiles.getUser({
            transaction
        });
        
        
        output.resume_documents = await private_profiles.getResume_documents({
            transaction
        });
        
        
        output.coaching_sessions = await private_profiles.getCoaching_sessions({
            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: '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.resume_documents,
        as: 'resume_documents',
        required: false,
      },

      {
        model: db.coaching_sessions,
        as: 'coaching_sessions',
        required: false,
      },


    ];

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

            
            if (filter.goals_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'private_profiles',
                        'goals_summary',
                        filter.goals_summary,
                    ),
                };
            }
            
            if (filter.focus_area) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'private_profiles',
                        'focus_area',
                        filter.focus_area,
                    ),
                };
            }
            
            if (filter.time_commitment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'private_profiles',
                        'time_commitment',
                        filter.time_commitment,
                    ),
                };
            }
            
            if (filter.constraints_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'private_profiles',
                        'constraints_notes',
                        filter.constraints_notes,
                    ),
                };
            }
            
            if (filter.ai_profile_draft) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'private_profiles',
                        'ai_profile_draft',
                        filter.ai_profile_draft,
                    ),
                };
            }
            
            if (filter.vision_statement) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'private_profiles',
                        'vision_statement',
                        filter.vision_statement,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      


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

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

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

        include = [
          {
            model: db.coaching_sessions,
            as: 'coaching_sessions_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  topic: {
                    [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.private_profiles.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(
                        'private_profiles',
                        'focus_area',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

