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

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

        const audits = await db.audits.create(
            {
                id: data.id || undefined,
        
        audit_number: data.audit_number
        ||
        null
            ,
            
        audit_type: data.audit_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        scope: data.scope
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await audits.setLead_auditor( data.lead_auditor || null, {
            transaction,
        });
        
        await audits.setSupplier( data.supplier || null, {
            transaction,
        });
        

        
        await audits.setMapped_clauses(data.mapped_clauses || [], {
            transaction,
        });
        

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

        return audits;
    }
    

    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 auditsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                audit_number: item.audit_number
            ||
            null
            ,
            
                audit_type: item.audit_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                scope: item.scope
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return audits;
    }

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

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


        

        const updatePayload = {};
        
        if (data.audit_number !== undefined) updatePayload.audit_number = data.audit_number;
        
        
        if (data.audit_type !== undefined) updatePayload.audit_type = data.audit_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.scope !== undefined) updatePayload.scope = data.scope;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.lead_auditor !== undefined) {
            await audits.setLead_auditor(
              
              data.lead_auditor,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await audits.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        

        
        
        if (data.mapped_clauses !== undefined) {
            await audits.setMapped_clauses(data.mapped_clauses, { transaction });
        }
        

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

        return audits;
    }

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

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

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


        return audits;
    }

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

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

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

        await audits.destroy({
            transaction
        });

        return audits;
    }

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

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

        if (!audits) {
            return audits;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.audit_findings_audit = await audits.getAudit_findings_audit({
            transaction
        });
        
        
        
        
        
        
        output.lead_auditor = await audits.getLead_auditor({
            transaction
        });
        
        
        output.supplier = await audits.getSupplier({
            transaction
        });
        
        
        output.audit_files = await audits.getAudit_files({
            transaction
        });
        
        
        output.mapped_clauses = await audits.getMapped_clauses({
            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.users,
        as: 'lead_auditor',
        
        where: filter.lead_auditor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lead_auditor.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.lead_auditor.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.clauses,
        as: 'mapped_clauses',
        required: false,
      },


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

    ];

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

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

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

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

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

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

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

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

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

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


      

      


      if (filter.mapped_clauses) {
        const searchTerms = filter.mapped_clauses.split('|');

        include = [
          {
            model: db.clauses,
            as: 'mapped_clauses_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  clause_code: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

