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

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

        const audit_findings = await db.audit_findings.create(
            {
                id: data.id || undefined,
        
        finding_number: data.finding_number
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        objective_evidence: data.objective_evidence
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await audit_findings.setAudit( data.audit || null, {
            transaction,
        });
        
        await audit_findings.setOwner( data.owner || null, {
            transaction,
        });
        
        await audit_findings.setRelated_capa( data.related_capa || null, {
            transaction,
        });
        

        

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

        return audit_findings;
    }
    

    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 audit_findingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                finding_number: item.finding_number
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                objective_evidence: item.objective_evidence
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return audit_findings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.finding_number !== undefined) updatePayload.finding_number = data.finding_number;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.objective_evidence !== undefined) updatePayload.objective_evidence = data.objective_evidence;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.audit !== undefined) {
            await audit_findings.setAudit(
              
              data.audit,
              
              { transaction }
            );
        }
        
        if (data.owner !== undefined) {
            await audit_findings.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.related_capa !== undefined) {
            await audit_findings.setRelated_capa(
              
              data.related_capa,
              
              { transaction }
            );
        }
        

        
        

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

        return audit_findings;
    }

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

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

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


        return audit_findings;
    }

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

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

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

        await audit_findings.destroy({
            transaction
        });

        return audit_findings;
    }

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

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

        if (!audit_findings) {
            return audit_findings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.audit = await audit_findings.getAudit({
            transaction
        });
        
        
        output.owner = await audit_findings.getOwner({
            transaction
        });
        
        
        output.evidence_files = await audit_findings.getEvidence_files({
            transaction
        });
        
        
        output.related_capa = await audit_findings.getRelated_capa({
            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.audits,
        as: 'audit',
        
        where: filter.audit ? {
          [Op.or]: [
            { id: { [Op.in]: filter.audit.split('|').map(term => Utils.uuid(term)) } },
            {
              audit_number: {
                [Op.or]: filter.audit.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.finding_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'audit_findings',
                        'finding_number',
                        filter.finding_number,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'audit_findings',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.objective_evidence) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'audit_findings',
                        'objective_evidence',
                        filter.objective_evidence,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

      



            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.audit_findings.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(
                        'audit_findings',
                        'finding_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

