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

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

        const inspection_characteristics = await db.inspection_characteristics.create(
            {
                id: data.id || undefined,
        
        sequence: data.sequence
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        data_type: data.data_type
        ||
        null
            ,
            
        target_value: data.target_value
        ||
        null
            ,
            
        lower_spec_limit: data.lower_spec_limit
        ||
        null
            ,
            
        upper_spec_limit: data.upper_spec_limit
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        sampling: data.sampling
        ||
        null
            ,
            
        required: data.required
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inspection_characteristics.setInspection_plan( data.inspection_plan || null, {
            transaction,
        });
        
        await inspection_characteristics.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return inspection_characteristics;
    }
    

    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 inspection_characteristicsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sequence: item.sequence
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                data_type: item.data_type
            ||
            null
            ,
            
                target_value: item.target_value
            ||
            null
            ,
            
                lower_spec_limit: item.lower_spec_limit
            ||
            null
            ,
            
                upper_spec_limit: item.upper_spec_limit
            ||
            null
            ,
            
                unit: item.unit
            ||
            null
            ,
            
                sampling: item.sampling
            ||
            null
            ,
            
                required: item.required
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return inspection_characteristics;
    }

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


        

        const updatePayload = {};
        
        if (data.sequence !== undefined) updatePayload.sequence = data.sequence;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.data_type !== undefined) updatePayload.data_type = data.data_type;
        
        
        if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
        
        
        if (data.lower_spec_limit !== undefined) updatePayload.lower_spec_limit = data.lower_spec_limit;
        
        
        if (data.upper_spec_limit !== undefined) updatePayload.upper_spec_limit = data.upper_spec_limit;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.sampling !== undefined) updatePayload.sampling = data.sampling;
        
        
        if (data.required !== undefined) updatePayload.required = data.required;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.inspection_plan !== undefined) {
            await inspection_characteristics.setInspection_plan(
              
              data.inspection_plan,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await inspection_characteristics.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return inspection_characteristics;
    }

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

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

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


        return inspection_characteristics;
    }

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

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

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

        await inspection_characteristics.destroy({
            transaction
        });

        return inspection_characteristics;
    }

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

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

        if (!inspection_characteristics) {
            return inspection_characteristics;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inspection_results_characteristic = await inspection_characteristics.getInspection_results_characteristic({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.inspection_plan = await inspection_characteristics.getInspection_plan({
            transaction
        });
        
        
        output.organizations = await inspection_characteristics.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.inspection_plans,
        as: 'inspection_plan',
        
        where: filter.inspection_plan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.inspection_plan.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.inspection_plan.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inspection_characteristics',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inspection_characteristics',
                        'unit',
                        filter.unit,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.data_type) {
                where = {
                    ...where,
                data_type: filter.data_type,
            };
            }
            
            if (filter.sampling) {
                where = {
                    ...where,
                sampling: filter.sampling,
            };
            }
            
            if (filter.required) {
                where = {
                    ...where,
                required: filter.required,
            };
            }
            


      

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

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

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

    
};

