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

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

        const inspections = await db.inspections.create(
            {
                id: data.id || undefined,
        
        inspection_number: data.inspection_number
        ||
        null
            ,
            
        inspection_type: data.inspection_type
        ||
        null
            ,
            
        inspected_at: data.inspected_at
        ||
        null
            ,
            
        result: data.result
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inspections.setInspection_plan( data.inspection_plan || null, {
            transaction,
        });
        
        await inspections.setItem( data.item || null, {
            transaction,
        });
        
        await inspections.setLot( data.lot || null, {
            transaction,
        });
        
        await inspections.setSerial( data.serial || null, {
            transaction,
        });
        
        await inspections.setWork_order( data.work_order || null, {
            transaction,
        });
        
        await inspections.setSupplier( data.supplier || null, {
            transaction,
        });
        
        await inspections.setInspected_by( data.inspected_by || null, {
            transaction,
        });
        

        

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

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

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

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

        return inspections;
    }

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

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


        

        const updatePayload = {};
        
        if (data.inspection_number !== undefined) updatePayload.inspection_number = data.inspection_number;
        
        
        if (data.inspection_type !== undefined) updatePayload.inspection_type = data.inspection_type;
        
        
        if (data.inspected_at !== undefined) updatePayload.inspected_at = data.inspected_at;
        
        
        if (data.result !== undefined) updatePayload.result = data.result;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.inspection_plan !== undefined) {
            await inspections.setInspection_plan(
              
              data.inspection_plan,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await inspections.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await inspections.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.serial !== undefined) {
            await inspections.setSerial(
              
              data.serial,
              
              { transaction }
            );
        }
        
        if (data.work_order !== undefined) {
            await inspections.setWork_order(
              
              data.work_order,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await inspections.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        
        if (data.inspected_by !== undefined) {
            await inspections.setInspected_by(
              
              data.inspected_by,
              
              { transaction }
            );
        }
        

        
        

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

        return inspections;
    }

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

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

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


        return inspections;
    }

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

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

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

        await inspections.destroy({
            transaction
        });

        return inspections;
    }

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

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

        if (!inspections) {
            return inspections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inspection_results_inspection = await inspections.getInspection_results_inspection({
            transaction
        });
        
        
        output.nonconformances_inspection = await inspections.getNonconformances_inspection({
            transaction
        });
        
        
        
        
        
        
        output.inspection_plan = await inspections.getInspection_plan({
            transaction
        });
        
        
        output.item = await inspections.getItem({
            transaction
        });
        
        
        output.lot = await inspections.getLot({
            transaction
        });
        
        
        output.serial = await inspections.getSerial({
            transaction
        });
        
        
        output.work_order = await inspections.getWork_order({
            transaction
        });
        
        
        output.supplier = await inspections.getSupplier({
            transaction
        });
        
        
        output.inspected_by = await inspections.getInspected_by({
            transaction
        });
        
        
        output.evidence = await inspections.getEvidence({
            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.inspection_plans,
        as: 'inspection_plan',
        
        where: filter.inspection_plan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.inspection_plan.split('|').map(term => Utils.uuid(term)) } },
            {
              plan_name: {
                [Op.or]: filter.inspection_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)) } },
            {
              item_name: {
                [Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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



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

    ];

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

            
            if (filter.inspection_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inspections',
                        'inspection_number',
                        filter.inspection_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inspections',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.inspection_type) {
                where = {
                    ...where,
                inspection_type: filter.inspection_type,
            };
            }
            
            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.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(
                        'inspections',
                        'inspection_number',
                        query,
                    ),
                ],
            };
        }

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

    
};

