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

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

        const kpi_measurements = await db.kpi_measurements.create(
            {
                id: data.id || undefined,
        
        measured_at: data.measured_at
        ||
        null
            ,
            
        value: data.value
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await kpi_measurements.setKpi_definition( data.kpi_definition || null, {
            transaction,
        });
        
        await kpi_measurements.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await kpi_measurements.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return kpi_measurements;
    }
    

    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_measurementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                measured_at: item.measured_at
            ||
            null
            ,
            
                value: item.value
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return kpi_measurements;
    }

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


        

        const updatePayload = {};
        
        if (data.measured_at !== undefined) updatePayload.measured_at = data.measured_at;
        
        
        if (data.value !== undefined) updatePayload.value = data.value;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.kpi_definition !== undefined) {
            await kpi_measurements.setKpi_definition(
              
              data.kpi_definition,
              
              { transaction }
            );
        }
        
        if (data.organization !== undefined) {
            await kpi_measurements.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await kpi_measurements.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return kpi_measurements;
    }

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

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

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


        return kpi_measurements;
    }

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

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

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

        await kpi_measurements.destroy({
            transaction
        });

        return kpi_measurements;
    }

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

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

        if (!kpi_measurements) {
            return kpi_measurements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.kpi_definition = await kpi_measurements.getKpi_definition({
            transaction
        });
        
        
        output.organization = await kpi_measurements.getOrganization({
            transaction
        });
        
        
        output.user = await kpi_measurements.getUser({
            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.kpi_definitions,
        as: 'kpi_definition',
        
        where: filter.kpi_definition ? {
          [Op.or]: [
            { id: { [Op.in]: filter.kpi_definition.split('|').map(term => Utils.uuid(term)) } },
            {
              kpi_name: {
                [Op.or]: filter.kpi_definition.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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


      

      
      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.kpi_measurements.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_measurements',
                        'source',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

