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

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

        const kpi_scores = await db.kpi_scores.create(
            {
                id: data.id || undefined,
        
        absensi_score: data.absensi_score
        ||
        null
            ,
            
        disiplin_score: data.disiplin_score
        ||
        null
            ,
            
        produktif_score: data.produktif_score
        ||
        null
            ,
            
        attitude_score: data.attitude_score
        ||
        null
            ,
            
        sop_score: data.sop_score
        ||
        null
            ,
            
        final_score: data.final_score
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        scored_at: data.scored_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await kpi_scores.setEmployee( data.employee || null, {
            transaction,
        });
        
        await kpi_scores.setKpi_period( data.kpi_period || null, {
            transaction,
        });
        
        await kpi_scores.setOutlet( data.outlet || null, {
            transaction,
        });
        
        await kpi_scores.setScored_by_user( data.scored_by_user || null, {
            transaction,
        });
        
        await kpi_scores.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return kpi_scores;
    }
    

    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 kpi_scoresData = data.map((item, index) => ({
                id: item.id || undefined,
                
                absensi_score: item.absensi_score
            ||
            null
            ,
            
                disiplin_score: item.disiplin_score
            ||
            null
            ,
            
                produktif_score: item.produktif_score
            ||
            null
            ,
            
                attitude_score: item.attitude_score
            ||
            null
            ,
            
                sop_score: item.sop_score
            ||
            null
            ,
            
                final_score: item.final_score
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                scored_at: item.scored_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return kpi_scores;
    }

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


        

        const updatePayload = {};
        
        if (data.absensi_score !== undefined) updatePayload.absensi_score = data.absensi_score;
        
        
        if (data.disiplin_score !== undefined) updatePayload.disiplin_score = data.disiplin_score;
        
        
        if (data.produktif_score !== undefined) updatePayload.produktif_score = data.produktif_score;
        
        
        if (data.attitude_score !== undefined) updatePayload.attitude_score = data.attitude_score;
        
        
        if (data.sop_score !== undefined) updatePayload.sop_score = data.sop_score;
        
        
        if (data.final_score !== undefined) updatePayload.final_score = data.final_score;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.scored_at !== undefined) updatePayload.scored_at = data.scored_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.employee !== undefined) {
            await kpi_scores.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.kpi_period !== undefined) {
            await kpi_scores.setKpi_period(
              
              data.kpi_period,
              
              { transaction }
            );
        }
        
        if (data.outlet !== undefined) {
            await kpi_scores.setOutlet(
              
              data.outlet,
              
              { transaction }
            );
        }
        
        if (data.scored_by_user !== undefined) {
            await kpi_scores.setScored_by_user(
              
              data.scored_by_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await kpi_scores.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return kpi_scores;
    }

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

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

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


        return kpi_scores;
    }

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

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

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

        await kpi_scores.destroy({
            transaction
        });

        return kpi_scores;
    }

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

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

        if (!kpi_scores) {
            return kpi_scores;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await kpi_scores.getEmployee({
            transaction
        });
        
        
        output.kpi_period = await kpi_scores.getKpi_period({
            transaction
        });
        
        
        output.outlet = await kpi_scores.getOutlet({
            transaction
        });
        
        
        output.scored_by_user = await kpi_scores.getScored_by_user({
            transaction
        });
        
        
        output.organizations = await kpi_scores.getOrganizations({
            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.employees,
        as: 'employee',
        
        where: filter.employee ? {
          [Op.or]: [
            { id: { [Op.in]: filter.employee.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.employee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      

      

      

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

        where = {
          ...where,
          organizationsId: {[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.kpi_scores.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(
                        'kpi_scores',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

