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

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

        const qa_evaluations = await db.qa_evaluations.create(
            {
                id: data.id || undefined,
        
        channel: data.channel
        ||
        null
            ,
            
        interaction_reference: data.interaction_reference
        ||
        null
            ,
            
        interaction_at: data.interaction_at
        ||
        null
            ,
            
        evaluated_at: data.evaluated_at
        ||
        null
            ,
            
        overall_score: data.overall_score
        ||
        null
            ,
            
        result: data.result
        ||
        null
            ,
            
        summary_notes: data.summary_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await qa_evaluations.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await qa_evaluations.setEvaluator( data.evaluator || null, {
            transaction,
        });
        
        await qa_evaluations.setAgent( data.agent || null, {
            transaction,
        });
        

        

        

        return qa_evaluations;
    }
    

    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 qa_evaluationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                channel: item.channel
            ||
            null
            ,
            
                interaction_reference: item.interaction_reference
            ||
            null
            ,
            
                interaction_at: item.interaction_at
            ||
            null
            ,
            
                evaluated_at: item.evaluated_at
            ||
            null
            ,
            
                overall_score: item.overall_score
            ||
            null
            ,
            
                result: item.result
            ||
            null
            ,
            
                summary_notes: item.summary_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return qa_evaluations;
    }

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


        

        const updatePayload = {};
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.interaction_reference !== undefined) updatePayload.interaction_reference = data.interaction_reference;
        
        
        if (data.interaction_at !== undefined) updatePayload.interaction_at = data.interaction_at;
        
        
        if (data.evaluated_at !== undefined) updatePayload.evaluated_at = data.evaluated_at;
        
        
        if (data.overall_score !== undefined) updatePayload.overall_score = data.overall_score;
        
        
        if (data.result !== undefined) updatePayload.result = data.result;
        
        
        if (data.summary_notes !== undefined) updatePayload.summary_notes = data.summary_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await qa_evaluations.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.evaluator !== undefined) {
            await qa_evaluations.setEvaluator(
              
              data.evaluator,
              
              { transaction }
            );
        }
        
        if (data.agent !== undefined) {
            await qa_evaluations.setAgent(
              
              data.agent,
              
              { transaction }
            );
        }
        

        
        

        

        return qa_evaluations;
    }

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

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

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


        return qa_evaluations;
    }

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

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

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

        await qa_evaluations.destroy({
            transaction
        });

        return qa_evaluations;
    }

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

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

        if (!qa_evaluations) {
            return qa_evaluations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.qa_scorecards_qa_evaluation = await qa_evaluations.getQa_scorecards_qa_evaluation({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.organization = await qa_evaluations.getOrganization({
            transaction
        });
        
        
        output.evaluator = await qa_evaluations.getEvaluator({
            transaction
        });
        
        
        output.agent = await qa_evaluations.getAgent({
            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.organizations,
        as: 'organization',
        
      },

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

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



    ];

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

            
            if (filter.interaction_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qa_evaluations',
                        'interaction_reference',
                        filter.interaction_reference,
                    ),
                };
            }
            
            if (filter.summary_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qa_evaluations',
                        'summary_notes',
                        filter.summary_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    evaluated_at: {
                    ...where.evaluated_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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.qa_evaluations.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(
                        'qa_evaluations',
                        'interaction_reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

