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

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

        const qa_inspection_plans = await db.qa_inspection_plans.create(
            {
                id: data.id || undefined,
        
        plan_code: data.plan_code
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        inspection_type: data.inspection_type
        ||
        null
            ,
            
        sampling_method: data.sampling_method
        ||
        null
            ,
            
        aql_level: data.aql_level
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await qa_inspection_plans.setItem( data.item || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.qa_inspection_plans.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: qa_inspection_plans.id,
            },
            data.attachments,
            options,
        );
        

        return qa_inspection_plans;
    }
    

    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_inspection_plansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                plan_code: item.plan_code
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                inspection_type: item.inspection_type
            ||
            null
            ,
            
                sampling_method: item.sampling_method
            ||
            null
            ,
            
                aql_level: item.aql_level
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                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_inspection_plans = await db.qa_inspection_plans.bulkCreate(qa_inspection_plansData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < qa_inspection_plans.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.qa_inspection_plans.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: qa_inspection_plans[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return qa_inspection_plans;
    }

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

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


        

        const updatePayload = {};
        
        if (data.plan_code !== undefined) updatePayload.plan_code = data.plan_code;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.inspection_type !== undefined) updatePayload.inspection_type = data.inspection_type;
        
        
        if (data.sampling_method !== undefined) updatePayload.sampling_method = data.sampling_method;
        
        
        if (data.aql_level !== undefined) updatePayload.aql_level = data.aql_level;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await qa_inspection_plans.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.qa_inspection_plans.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: qa_inspection_plans.id,
            },
            data.attachments,
            options,
        );
        

        return qa_inspection_plans;
    }

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

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

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


        return qa_inspection_plans;
    }

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

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

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

        await qa_inspection_plans.destroy({
            transaction
        });

        return qa_inspection_plans;
    }

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

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

        if (!qa_inspection_plans) {
            return qa_inspection_plans;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.qa_inspections_plan = await qa_inspection_plans.getQa_inspections_plan({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.item = await qa_inspection_plans.getItem({
            transaction
        });
        
        
        output.attachments = await qa_inspection_plans.getAttachments({
            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.items,
        as: 'item',
        
        where: filter.item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

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

            
            

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

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

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

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

            
            if (filter.inspection_type) {
                where = {
                    ...where,
                inspection_type: filter.inspection_type,
            };
            }
            
            if (filter.sampling_method) {
                where = {
                    ...where,
                sampling_method: filter.sampling_method,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



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

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

    
};

