
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
            ,
            
        target_value: data.target_value
        ||
        null
            ,
            
        lower_limit: data.lower_limit
        ||
        null
            ,
            
        upper_limit: data.upper_limit
        ||
        null
            ,
            
        unit: data.unit
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        method: data.method
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await qa_characteristics.setQa_plan( data.qa_plan || 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
            ,
            
                target_value: item.target_value
            ||
            null
            ,
            
                lower_limit: item.lower_limit
            ||
            null
            ,
            
                upper_limit: item.upper_limit
            ||
            null
            ,
            
                unit: item.unit
            ||
            null
            ,
            
                severity: item.severity
            ||
            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 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.target_value !== undefined) updatePayload.target_value = data.target_value;
        
        
        if (data.lower_limit !== undefined) updatePayload.lower_limit = data.lower_limit;
        
        
        if (data.upper_limit !== undefined) updatePayload.upper_limit = data.upper_limit;
        
        
        if (data.unit !== undefined) updatePayload.unit = data.unit;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.method !== undefined) updatePayload.method = data.method;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.qa_plan !== undefined) {
            await qa_characteristics.setQa_plan(
              
              data.qa_plan,
              
              { 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_qa_characteristic = await qa_characteristics.getQa_results_qa_characteristic({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.qa_plan = await qa_characteristics.getQa_plan({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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



    ];

        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.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_limitRange) {
                const [start, end] = filter.lower_limitRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    upper_limit: {
                    ...where.upper_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.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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, ) {
        let where = {};
        
        

        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,
        }));
    }

    
};

