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

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

        const qa_inspections = await db.qa_inspections.create(
            {
                id: data.id || undefined,
        
        inspection_number: data.inspection_number
        ||
        null
            ,
            
        context: data.context
        ||
        null
            ,
            
        inspected_at: data.inspected_at
        ||
        null
            ,
            
        result: data.result
        ||
        null
            ,
            
        sample_size: data.sample_size
        ||
        null
            ,
            
        defect_count: data.defect_count
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await qa_inspections.setPlan( data.plan || null, {
            transaction,
        });
        
        await qa_inspections.setItem( data.item || null, {
            transaction,
        });
        
        await qa_inspections.setLot( data.lot || null, {
            transaction,
        });
        
        await qa_inspections.setProduction_order( data.production_order || null, {
            transaction,
        });
        
        await qa_inspections.setOperation( data.operation || null, {
            transaction,
        });
        
        await qa_inspections.setInspector( data.inspector || null, {
            transaction,
        });
        

        

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

        return qa_inspections;
    }
    

    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_inspectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                inspection_number: item.inspection_number
            ||
            null
            ,
            
                context: item.context
            ||
            null
            ,
            
                inspected_at: item.inspected_at
            ||
            null
            ,
            
                result: item.result
            ||
            null
            ,
            
                sample_size: item.sample_size
            ||
            null
            ,
            
                defect_count: item.defect_count
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return qa_inspections;
    }

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

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


        

        const updatePayload = {};
        
        if (data.inspection_number !== undefined) updatePayload.inspection_number = data.inspection_number;
        
        
        if (data.context !== undefined) updatePayload.context = data.context;
        
        
        if (data.inspected_at !== undefined) updatePayload.inspected_at = data.inspected_at;
        
        
        if (data.result !== undefined) updatePayload.result = data.result;
        
        
        if (data.sample_size !== undefined) updatePayload.sample_size = data.sample_size;
        
        
        if (data.defect_count !== undefined) updatePayload.defect_count = data.defect_count;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.plan !== undefined) {
            await qa_inspections.setPlan(
              
              data.plan,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await qa_inspections.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await qa_inspections.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.production_order !== undefined) {
            await qa_inspections.setProduction_order(
              
              data.production_order,
              
              { transaction }
            );
        }
        
        if (data.operation !== undefined) {
            await qa_inspections.setOperation(
              
              data.operation,
              
              { transaction }
            );
        }
        
        if (data.inspector !== undefined) {
            await qa_inspections.setInspector(
              
              data.inspector,
              
              { transaction }
            );
        }
        

        
        

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

        return qa_inspections;
    }

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

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

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


        return qa_inspections;
    }

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

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

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

        await qa_inspections.destroy({
            transaction
        });

        return qa_inspections;
    }

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

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

        if (!qa_inspections) {
            return qa_inspections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.nonconformances_inspection = await qa_inspections.getNonconformances_inspection({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.plan = await qa_inspections.getPlan({
            transaction
        });
        
        
        output.item = await qa_inspections.getItem({
            transaction
        });
        
        
        output.lot = await qa_inspections.getLot({
            transaction
        });
        
        
        output.production_order = await qa_inspections.getProduction_order({
            transaction
        });
        
        
        output.operation = await qa_inspections.getOperation({
            transaction
        });
        
        
        output.inspector = await qa_inspections.getInspector({
            transaction
        });
        
        
        output.attachments = await qa_inspections.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.qa_inspection_plans,
        as: 'plan',
        
        where: filter.plan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.plan.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.inventory_lots,
        as: 'lot',
        
        where: filter.lot ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lot.split('|').map(term => Utils.uuid(term)) } },
            {
              lot_number: {
                [Op.or]: filter.lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.users,
        as: 'inspector',
        
        where: filter.inspector ? {
          [Op.or]: [
            { id: { [Op.in]: filter.inspector.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.inspector.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.inspection_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qa_inspections',
                        'inspection_number',
                        filter.inspection_number,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'qa_inspections',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.context) {
                where = {
                    ...where,
                context: filter.context,
            };
            }
            
            if (filter.result) {
                where = {
                    ...where,
                result: filter.result,
            };
            }
            


      

      

      

      

      

      



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

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

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

    
};

