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

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

        const brain_profiles = await db.brain_profiles.create(
            {
                id: data.id || undefined,
        
        profile_name: data.profile_name
        ||
        null
            ,
            
        profile_category: data.profile_category
        ||
        null
            ,
            
        goal_statement: data.goal_statement
        ||
        null
            ,
            
        behavior_rules: data.behavior_rules
        ||
        null
            ,
            
        preferred_sources_description: data.preferred_sources_description
        ||
        null
            ,
            
        citation_strictness: data.citation_strictness
        ||
        null
            ,
            
        creativity_level: data.creativity_level
        ||
        null
            ,
            
        compliance_strictness: data.compliance_strictness
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return brain_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 brain_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                profile_name: item.profile_name
            ||
            null
            ,
            
                profile_category: item.profile_category
            ||
            null
            ,
            
                goal_statement: item.goal_statement
            ||
            null
            ,
            
                behavior_rules: item.behavior_rules
            ||
            null
            ,
            
                preferred_sources_description: item.preferred_sources_description
            ||
            null
            ,
            
                citation_strictness: item.citation_strictness
            ||
            null
            ,
            
                creativity_level: item.creativity_level
            ||
            null
            ,
            
                compliance_strictness: item.compliance_strictness
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return brain_profiles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.profile_name !== undefined) updatePayload.profile_name = data.profile_name;
        
        
        if (data.profile_category !== undefined) updatePayload.profile_category = data.profile_category;
        
        
        if (data.goal_statement !== undefined) updatePayload.goal_statement = data.goal_statement;
        
        
        if (data.behavior_rules !== undefined) updatePayload.behavior_rules = data.behavior_rules;
        
        
        if (data.preferred_sources_description !== undefined) updatePayload.preferred_sources_description = data.preferred_sources_description;
        
        
        if (data.citation_strictness !== undefined) updatePayload.citation_strictness = data.citation_strictness;
        
        
        if (data.creativity_level !== undefined) updatePayload.creativity_level = data.creativity_level;
        
        
        if (data.compliance_strictness !== undefined) updatePayload.compliance_strictness = data.compliance_strictness;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return brain_profiles;
    }

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

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

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


        return brain_profiles;
    }

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

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

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

        await brain_profiles.destroy({
            transaction
        });

        return brain_profiles;
    }

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

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

        if (!brain_profiles) {
            return brain_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.campaign_brain_configs_brain_profile = await brain_profiles.getCampaign_brain_configs_brain_profile({
            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 = [



    ];

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

            
            if (filter.profile_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brain_profiles',
                        'profile_name',
                        filter.profile_name,
                    ),
                };
            }
            
            if (filter.goal_statement) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brain_profiles',
                        'goal_statement',
                        filter.goal_statement,
                    ),
                };
            }
            
            if (filter.behavior_rules) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brain_profiles',
                        'behavior_rules',
                        filter.behavior_rules,
                    ),
                };
            }
            
            if (filter.preferred_sources_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brain_profiles',
                        'preferred_sources_description',
                        filter.preferred_sources_description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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




            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.brain_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(
                        'brain_profiles',
                        'profile_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

