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

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

        const inspection_plans = await db.inspection_plans.create(
            {
                id: data.id || undefined,
        
        plan_name: data.plan_name
        ||
        null
            ,
            
        sampling_method: data.sampling_method
        ||
        null
            ,
            
        sample_size: data.sample_size
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inspection_plans.setQuality_standard( data.quality_standard || null, {
            transaction,
        });
        

        

        

        return 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 inspection_plansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                plan_name: item.plan_name
            ||
            null
            ,
            
                sampling_method: item.sampling_method
            ||
            null
            ,
            
                sample_size: item.sample_size
            ||
            null
            ,
            
                status: item.status
            ||
            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 inspection_plans = await db.inspection_plans.bulkCreate(inspection_plansData, { transaction });

        // For each item created, replace relation files
        

        return inspection_plans;
    }

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

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


        

        const updatePayload = {};
        
        if (data.plan_name !== undefined) updatePayload.plan_name = data.plan_name;
        
        
        if (data.sampling_method !== undefined) updatePayload.sampling_method = data.sampling_method;
        
        
        if (data.sample_size !== undefined) updatePayload.sample_size = data.sample_size;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.quality_standard !== undefined) {
            await inspection_plans.setQuality_standard(
              
              data.quality_standard,
              
              { transaction }
            );
        }
        

        
        

        

        return inspection_plans;
    }

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

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

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


        return inspection_plans;
    }

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

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

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

        await inspection_plans.destroy({
            transaction
        });

        return inspection_plans;
    }

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

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

        if (!inspection_plans) {
            return inspection_plans;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inspections_inspection_plan = await inspection_plans.getInspections_inspection_plan({
            transaction
        });
        
        
        
        
        
        
        
        output.quality_standard = await inspection_plans.getQuality_standard({
            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.quality_standards,
        as: 'quality_standard',
        
        where: filter.quality_standard ? {
          [Op.or]: [
            { id: { [Op.in]: filter.quality_standard.split('|').map(term => Utils.uuid(term)) } },
            {
              standard_name: {
                [Op.or]: filter.quality_standard.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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


      



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

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

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

    
};

