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

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

        const brand_voice_profiles = await db.brand_voice_profiles.create(
            {
                id: data.id || undefined,
        
        profile_name: data.profile_name
        ||
        null
            ,
            
        voice_description: data.voice_description
        ||
        null
            ,
            
        do_say_examples: data.do_say_examples
        ||
        null
            ,
            
        dont_say_examples: data.dont_say_examples
        ||
        null
            ,
            
        english_variant: data.english_variant
        ||
        null
            ,
            
        reading_level_target: data.reading_level_target
        ||
        null
            ,
            
        formality_level: data.formality_level
        ||
        null
            ,
            
        empathy_level: data.empathy_level
        ||
        null
            ,
            
        energy_level: data.energy_level
        ||
        null
            ,
            
        humor_level: data.humor_level
        ||
        null
            ,
            
        risk_tolerance: data.risk_tolerance
        ||
        null
            ,
            
        show_reasoning_trace: data.show_reasoning_trace
        ||
        false
        
            ,
            
        is_default: data.is_default
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await brand_voice_profiles.setBrand( data.brand || null, {
            transaction,
        });
        

        

        

        return brand_voice_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 brand_voice_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                profile_name: item.profile_name
            ||
            null
            ,
            
                voice_description: item.voice_description
            ||
            null
            ,
            
                do_say_examples: item.do_say_examples
            ||
            null
            ,
            
                dont_say_examples: item.dont_say_examples
            ||
            null
            ,
            
                english_variant: item.english_variant
            ||
            null
            ,
            
                reading_level_target: item.reading_level_target
            ||
            null
            ,
            
                formality_level: item.formality_level
            ||
            null
            ,
            
                empathy_level: item.empathy_level
            ||
            null
            ,
            
                energy_level: item.energy_level
            ||
            null
            ,
            
                humor_level: item.humor_level
            ||
            null
            ,
            
                risk_tolerance: item.risk_tolerance
            ||
            null
            ,
            
                show_reasoning_trace: item.show_reasoning_trace
            ||
            false
        
            ,
            
                is_default: item.is_default
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return brand_voice_profiles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.profile_name !== undefined) updatePayload.profile_name = data.profile_name;
        
        
        if (data.voice_description !== undefined) updatePayload.voice_description = data.voice_description;
        
        
        if (data.do_say_examples !== undefined) updatePayload.do_say_examples = data.do_say_examples;
        
        
        if (data.dont_say_examples !== undefined) updatePayload.dont_say_examples = data.dont_say_examples;
        
        
        if (data.english_variant !== undefined) updatePayload.english_variant = data.english_variant;
        
        
        if (data.reading_level_target !== undefined) updatePayload.reading_level_target = data.reading_level_target;
        
        
        if (data.formality_level !== undefined) updatePayload.formality_level = data.formality_level;
        
        
        if (data.empathy_level !== undefined) updatePayload.empathy_level = data.empathy_level;
        
        
        if (data.energy_level !== undefined) updatePayload.energy_level = data.energy_level;
        
        
        if (data.humor_level !== undefined) updatePayload.humor_level = data.humor_level;
        
        
        if (data.risk_tolerance !== undefined) updatePayload.risk_tolerance = data.risk_tolerance;
        
        
        if (data.show_reasoning_trace !== undefined) updatePayload.show_reasoning_trace = data.show_reasoning_trace;
        
        
        if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.brand !== undefined) {
            await brand_voice_profiles.setBrand(
              
              data.brand,
              
              { transaction }
            );
        }
        

        
        

        

        return brand_voice_profiles;
    }

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

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

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


        return brand_voice_profiles;
    }

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

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

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

        await brand_voice_profiles.destroy({
            transaction
        });

        return brand_voice_profiles;
    }

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

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

        if (!brand_voice_profiles) {
            return brand_voice_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ad_projects_brand_voice_profile = await brand_voice_profiles.getAd_projects_brand_voice_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.brand = await brand_voice_profiles.getBrand({
            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.brands,
        as: 'brand',
        
        where: filter.brand ? {
          [Op.or]: [
            { id: { [Op.in]: filter.brand.split('|').map(term => Utils.uuid(term)) } },
            {
              brand_name: {
                [Op.or]: filter.brand.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.profile_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brand_voice_profiles',
                        'profile_name',
                        filter.profile_name,
                    ),
                };
            }
            
            if (filter.voice_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brand_voice_profiles',
                        'voice_description',
                        filter.voice_description,
                    ),
                };
            }
            
            if (filter.do_say_examples) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brand_voice_profiles',
                        'do_say_examples',
                        filter.do_say_examples,
                    ),
                };
            }
            
            if (filter.dont_say_examples) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brand_voice_profiles',
                        'dont_say_examples',
                        filter.dont_say_examples,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.english_variant) {
                where = {
                    ...where,
                english_variant: filter.english_variant,
            };
            }
            
            if (filter.show_reasoning_trace) {
                where = {
                    ...where,
                show_reasoning_trace: filter.show_reasoning_trace,
            };
            }
            
            if (filter.is_default) {
                where = {
                    ...where,
                is_default: filter.is_default,
            };
            }
            


      



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

        const records = await db.brand_voice_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,
        }));
    }

    
};

