
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,
        
        name: data.name
        ||
        null
            ,
            
        plan_number: data.plan_number
        ||
        null
            ,
            
        inspection_type: data.inspection_type
        ||
        null
            ,
            
        revision: data.revision
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await inspection_plans.setMaterial( data.material || null, {
            transaction,
        });
        
        await inspection_plans.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        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,
                
                name: item.name
            ||
            null
            ,
            
                plan_number: item.plan_number
            ||
            null
            ,
            
                inspection_type: item.inspection_type
            ||
            null
            ,
            
                revision: item.revision
            ||
            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
        
        for (let i = 0; i < inspection_plans.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.inspection_plans.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: inspection_plans[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return inspection_plans;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.plan_number !== undefined) updatePayload.plan_number = data.plan_number;
        
        
        if (data.inspection_type !== undefined) updatePayload.inspection_type = data.inspection_type;
        
        
        if (data.revision !== undefined) updatePayload.revision = data.revision;
        
        
        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.material !== undefined) {
            await inspection_plans.setMaterial(
              
              data.material,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await inspection_plans.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        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.inspection_characteristics_inspection_plan = await inspection_plans.getInspection_characteristics_inspection_plan({
            transaction
        });
        
        
        output.inspections_inspection_plan = await inspection_plans.getInspections_inspection_plan({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.material = await inspection_plans.getMaterial({
            transaction
        });
        
        
        output.attachments = await inspection_plans.getAttachments({
            transaction
        });
        
        
        output.organizations = await inspection_plans.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.materials,
        as: 'material',
        
        where: filter.material ? {
          [Op.or]: [
            { id: { [Op.in]: filter.material.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.material.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inspection_plans',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.plan_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inspection_plans',
                        'plan_number',
                        filter.plan_number,
                    ),
                };
            }
            
            if (filter.revision) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inspection_plans',
                        'revision',
                        filter.revision,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'inspection_plans',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            

            

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

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

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

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

    
};

