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

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

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

        
        await quality_inspections.setItem( data.item || null, {
            transaction,
        });
        
        await quality_inspections.setProduction_order( data.production_order || null, {
            transaction,
        });
        
        await quality_inspections.setLot( data.lot || null, {
            transaction,
        });
        
        await quality_inspections.setInspected_by( data.inspected_by || null, {
            transaction,
        });
        
        await quality_inspections.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return quality_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 quality_inspectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                inspection_type: item.inspection_type
            ||
            null
            ,
            
                inspection_at: item.inspection_at
            ||
            null
            ,
            
                result: item.result
            ||
            null
            ,
            
                summary: item.summary
            ||
            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 quality_inspections = await db.quality_inspections.bulkCreate(quality_inspectionsData, { transaction });

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

        return quality_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 quality_inspections = await db.quality_inspections.findByPk(id, {}, {transaction});


        

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

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

        
        
        if (data.item !== undefined) {
            await quality_inspections.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.production_order !== undefined) {
            await quality_inspections.setProduction_order(
              
              data.production_order,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await quality_inspections.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.inspected_by !== undefined) {
            await quality_inspections.setInspected_by(
              
              data.inspected_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await quality_inspections.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return quality_inspections;
    }

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

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

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


        return quality_inspections;
    }

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

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

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

        await quality_inspections.destroy({
            transaction
        });

        return quality_inspections;
    }

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

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

        if (!quality_inspections) {
            return quality_inspections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.nonconformances_quality_inspection = await quality_inspections.getNonconformances_quality_inspection({
            transaction
        });
        
        
        
        
        
        output.item = await quality_inspections.getItem({
            transaction
        });
        
        
        output.production_order = await quality_inspections.getProduction_order({
            transaction
        });
        
        
        output.lot = await quality_inspections.getLot({
            transaction
        });
        
        
        output.inspected_by = await quality_inspections.getInspected_by({
            transaction
        });
        
        
        output.attachments = await quality_inspections.getAttachments({
            transaction
        });
        
        
        output.organizations = await quality_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.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.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.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.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.organizations,
        as: 'organizations',
        
      },



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

    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    inspection_at: {
                    ...where.inspection_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.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.quality_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(
                        'quality_inspections',
                        'summary',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

