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

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

        const feedback_entries = await db.feedback_entries.create(
            {
                id: data.id || undefined,
        
        given_at: data.given_at
        ||
        null
            ,
            
        overall_score: data.overall_score
        ||
        null
            ,
            
        compliance_score: data.compliance_score
        ||
        null
            ,
            
        brand_fit_score: data.brand_fit_score
        ||
        null
            ,
            
        conversion_intent_score: data.conversion_intent_score
        ||
        null
            ,
            
        empathy_score: data.empathy_score
        ||
        null
            ,
            
        risk_boldness_score: data.risk_boldness_score
        ||
        null
            ,
            
        freeform_notes: data.freeform_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await feedback_entries.setGeneration_output( data.generation_output || null, {
            transaction,
        });
        
        await feedback_entries.setGiven_by( data.given_by || null, {
            transaction,
        });
        

        

        

        return feedback_entries;
    }
    

    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 feedback_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                given_at: item.given_at
            ||
            null
            ,
            
                overall_score: item.overall_score
            ||
            null
            ,
            
                compliance_score: item.compliance_score
            ||
            null
            ,
            
                brand_fit_score: item.brand_fit_score
            ||
            null
            ,
            
                conversion_intent_score: item.conversion_intent_score
            ||
            null
            ,
            
                empathy_score: item.empathy_score
            ||
            null
            ,
            
                risk_boldness_score: item.risk_boldness_score
            ||
            null
            ,
            
                freeform_notes: item.freeform_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return feedback_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.given_at !== undefined) updatePayload.given_at = data.given_at;
        
        
        if (data.overall_score !== undefined) updatePayload.overall_score = data.overall_score;
        
        
        if (data.compliance_score !== undefined) updatePayload.compliance_score = data.compliance_score;
        
        
        if (data.brand_fit_score !== undefined) updatePayload.brand_fit_score = data.brand_fit_score;
        
        
        if (data.conversion_intent_score !== undefined) updatePayload.conversion_intent_score = data.conversion_intent_score;
        
        
        if (data.empathy_score !== undefined) updatePayload.empathy_score = data.empathy_score;
        
        
        if (data.risk_boldness_score !== undefined) updatePayload.risk_boldness_score = data.risk_boldness_score;
        
        
        if (data.freeform_notes !== undefined) updatePayload.freeform_notes = data.freeform_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.generation_output !== undefined) {
            await feedback_entries.setGeneration_output(
              
              data.generation_output,
              
              { transaction }
            );
        }
        
        if (data.given_by !== undefined) {
            await feedback_entries.setGiven_by(
              
              data.given_by,
              
              { transaction }
            );
        }
        

        
        

        

        return feedback_entries;
    }

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

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

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


        return feedback_entries;
    }

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

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

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

        await feedback_entries.destroy({
            transaction
        });

        return feedback_entries;
    }

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

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

        if (!feedback_entries) {
            return feedback_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.generation_output = await feedback_entries.getGeneration_output({
            transaction
        });
        
        
        output.given_by = await feedback_entries.getGiven_by({
            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.generation_outputs,
        as: 'generation_output',
        
        where: filter.generation_output ? {
          [Op.or]: [
            { id: { [Op.in]: filter.generation_output.split('|').map(term => Utils.uuid(term)) } },
            {
              output_title: {
                [Op.or]: filter.generation_output.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.freeform_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'feedback_entries',
                        'freeform_notes',
                        filter.freeform_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      



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

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

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

    
};

