
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_type: data.inspection_type
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        overall_result: data.overall_result
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await qa_inspections.setPlant( data.plant || null, {
            transaction,
        });
        
        await qa_inspections.setInspection_plan( data.inspection_plan || null, {
            transaction,
        });
        
        await qa_inspections.setItem( data.item || null, {
            transaction,
        });
        
        await qa_inspections.setLot( data.lot || null, {
            transaction,
        });
        
        await qa_inspections.setWork_order( data.work_order || null, {
            transaction,
        });
        
        await qa_inspections.setInspector_user( data.inspector_user || null, {
            transaction,
        });
        
        await qa_inspections.setOrganizations( data.organizations || 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_type: item.inspection_type
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                overall_result: item.overall_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 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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.inspection_type !== undefined) updatePayload.inspection_type = data.inspection_type;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.overall_result !== undefined) updatePayload.overall_result = data.overall_result;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.plant !== undefined) {
            await qa_inspections.setPlant(
              
              data.plant,
              
              { transaction }
            );
        }
        
        if (data.inspection_plan !== undefined) {
            await qa_inspections.setInspection_plan(
              
              data.inspection_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.work_order !== undefined) {
            await qa_inspections.setWork_order(
              
              data.work_order,
              
              { transaction }
            );
        }
        
        if (data.inspector_user !== undefined) {
            await qa_inspections.setInspector_user(
              
              data.inspector_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await qa_inspections.setOrganizations(
              
              data.organizations,
              
              { 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.qa_results_inspection = await qa_inspections.getQa_results_inspection({
            transaction
        });
        
        
        output.nonconformances_inspection = await qa_inspections.getNonconformances_inspection({
            transaction
        });
        
        
        
        
        
        
        output.plant = await qa_inspections.getPlant({
            transaction
        });
        
        
        output.inspection_plan = await qa_inspections.getInspection_plan({
            transaction
        });
        
        
        output.item = await qa_inspections.getItem({
            transaction
        });
        
        
        output.lot = await qa_inspections.getLot({
            transaction
        });
        
        
        output.work_order = await qa_inspections.getWork_order({
            transaction
        });
        
        
        output.inspector_user = await qa_inspections.getInspector_user({
            transaction
        });
        
        
        output.attachments = await qa_inspections.getAttachments({
            transaction
        });
        
        
        output.organizations = await qa_inspections.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            scheduled_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    completed_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    scheduled_at: {
                    ...where.scheduled_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.started_atRange) {
                const [start, end] = filter.started_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    started_at: {
                    ...where.started_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.completed_atRange) {
                const [start, end] = filter.completed_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    completed_at: {
                    ...where.completed_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.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.overall_result) {
                where = {
                    ...where,
                overall_result: filter.overall_result,
            };
            }
            


      

      

      

      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'qa_inspections',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

