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

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

        const qa_checklist_items = await db.qa_checklist_items.create(
            {
                id: data.id || undefined,
        
        sequence_number: data.sequence_number
        ||
        null
            ,
            
        check_name: data.check_name
        ||
        null
            ,
            
        value_type: data.value_type
        ||
        null
            ,
            
        lower_limit: data.lower_limit
        ||
        null
            ,
            
        upper_limit: data.upper_limit
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await qa_checklist_items.setQa_checklist( data.qa_checklist || null, {
            transaction,
        });
        

        

        

        return qa_checklist_items;
    }
    

    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_checklist_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sequence_number: item.sequence_number
            ||
            null
            ,
            
                check_name: item.check_name
            ||
            null
            ,
            
                value_type: item.value_type
            ||
            null
            ,
            
                lower_limit: item.lower_limit
            ||
            null
            ,
            
                upper_limit: item.upper_limit
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return qa_checklist_items;
    }

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

        const qa_checklist_items = await db.qa_checklist_items.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.sequence_number !== undefined) updatePayload.sequence_number = data.sequence_number;
        
        
        if (data.check_name !== undefined) updatePayload.check_name = data.check_name;
        
        
        if (data.value_type !== undefined) updatePayload.value_type = data.value_type;
        
        
        if (data.lower_limit !== undefined) updatePayload.lower_limit = data.lower_limit;
        
        
        if (data.upper_limit !== undefined) updatePayload.upper_limit = data.upper_limit;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.qa_checklist !== undefined) {
            await qa_checklist_items.setQa_checklist(
              
              data.qa_checklist,
              
              { transaction }
            );
        }
        

        
        

        

        return qa_checklist_items;
    }

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

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

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


        return qa_checklist_items;
    }

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

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

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

        await qa_checklist_items.destroy({
            transaction
        });

        return qa_checklist_items;
    }

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

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

        if (!qa_checklist_items) {
            return qa_checklist_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.qa_measurements_qa_checklist_item = await qa_checklist_items.getQa_measurements_qa_checklist_item({
            transaction
        });
        
        
        
        
        
        
        output.qa_checklist = await qa_checklist_items.getQa_checklist({
            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_checklists,
        as: 'qa_checklist',
        
        where: filter.qa_checklist ? {
          [Op.or]: [
            { id: { [Op.in]: filter.qa_checklist.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.qa_checklist.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.check_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qa_checklist_items',
                        'check_name',
                        filter.check_name,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qa_checklist_items',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            

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

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

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


      



            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_checklist_items.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_checklist_items',
                        'check_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

