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

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

        const qa_characteristics = await db.qa_characteristics.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        data_type: data.data_type
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        lower_spec: data.lower_spec
        ||
        null
            ,
            
        upper_spec: data.upper_spec
        ||
        null
            ,
            
        result_required: data.result_required
        ||
        null
            ,
            
        sequence: data.sequence
        ||
        null
            ,
            
        method: data.method
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return qa_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 qa_characteristicsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                data_type: item.data_type
            ||
            null
            ,
            
                unit: item.unit
            ||
            null
            ,
            
                lower_spec: item.lower_spec
            ||
            null
            ,
            
                upper_spec: item.upper_spec
            ||
            null
            ,
            
                result_required: item.result_required
            ||
            null
            ,
            
                sequence: item.sequence
            ||
            null
            ,
            
                method: item.method
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.data_type !== undefined) updatePayload.data_type = data.data_type;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.lower_spec !== undefined) updatePayload.lower_spec = data.lower_spec;
        
        
        if (data.upper_spec !== undefined) updatePayload.upper_spec = data.upper_spec;
        
        
        if (data.result_required !== undefined) updatePayload.result_required = data.result_required;
        
        
        if (data.sequence !== undefined) updatePayload.sequence = data.sequence;
        
        
        if (data.method !== undefined) updatePayload.method = data.method;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return qa_characteristics;
    }

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

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

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


        return qa_characteristics;
    }

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

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

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

        await qa_characteristics.destroy({
            transaction
        });

        return qa_characteristics;
    }

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

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

        if (!qa_characteristics) {
            return qa_characteristics;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.qa_results_characteristic = await qa_characteristics.getQa_results_characteristic({
            transaction
        });
        
        
        
        
        
        
        
        output.inspection_plan = await qa_characteristics.getInspection_plan({
            transaction
        });
        
        
        output.organizations = await qa_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.qa_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(
                        'qa_characteristics',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qa_characteristics',
                        'unit',
                        filter.unit,
                    ),
                };
            }
            
            if (filter.method) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qa_characteristics',
                        'method',
                        filter.method,
                    ),
                };
            }
            

            
            

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

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

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

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

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

            
            if (filter.data_type) {
                where = {
                    ...where,
                data_type: filter.data_type,
            };
            }
            
            if (filter.result_required) {
                where = {
                    ...where,
                result_required: filter.result_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.qa_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(
                        'qa_characteristics',
                        'name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.qa_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,
        }));
    }

    
};

