
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const TenantAccess = require('./tenantAccess');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class ExceptionsDBApi {
    

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

        const exceptions = await db.exceptions.create(
            {
                id: data.id || undefined,
        
        exception_name: data.exception_name
        ||
        null
            ,
            
        exception_type: data.exception_type
        ||
        null
            ,
            
        subject: data.subject
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        granted_at: data.granted_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        revoked_at: data.revoked_at
        ||
        null
            ,
            
        followup_review_required: data.followup_review_required
        ||
        false
        
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await exceptions.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await exceptions.setApprover_user( data.approver_user || null, {
            transaction,
        });
        

        
        await exceptions.setLinked_artifacts(data.linked_artifacts || [], {
            transaction,
        });
        

        

        return exceptions;
    }
    

    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 exceptionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                exception_name: item.exception_name
            ||
            null
            ,
            
                exception_type: item.exception_type
            ||
            null
            ,
            
                subject: item.subject
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                granted_at: item.granted_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                revoked_at: item.revoked_at
            ||
            null
            ,
            
                followup_review_required: item.followup_review_required
            ||
            false
        
            ,
            
                status: item.status
            ||
            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 exceptions = await db.exceptions.bulkCreate(exceptionsData, { transaction });

        // For each item created, replace relation files
        

        return exceptions;
    }

    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 exceptions = await TenantAccess.findByPkOrThrow(db.exceptions, id, options);


        

        const updatePayload = {};
        
        if (data.exception_name !== undefined) updatePayload.exception_name = data.exception_name;
        
        
        if (data.exception_type !== undefined) updatePayload.exception_type = data.exception_type;
        
        
        if (data.subject !== undefined) updatePayload.subject = data.subject;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.granted_at !== undefined) updatePayload.granted_at = data.granted_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_at;
        
        
        if (data.followup_review_required !== undefined) updatePayload.followup_review_required = data.followup_review_required;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await exceptions.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.approver_user !== undefined) {
            await exceptions.setApprover_user(
              
              data.approver_user,
              
              { transaction }
            );
        }
        

        
        
        if (data.linked_artifacts !== undefined) {
            await exceptions.setLinked_artifacts(data.linked_artifacts, { transaction });
        }
        

        

        return exceptions;
    }

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

        const exceptions = await TenantAccess.findAllByIds(db.exceptions, ids, options);

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


        return exceptions;
    }

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

        const exceptions = await TenantAccess.findByPkOrThrow(db.exceptions, id, options);

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

        await exceptions.destroy({
            transaction
        });

        return exceptions;
    }

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

        const exceptions = await TenantAccess.findOne(db.exceptions, where, options);

        if (!exceptions) {
            return exceptions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await exceptions.getOrganization({
            transaction
        });
        
        
        output.approver_user = await exceptions.getApprover_user({
            transaction
        });
        
        
        output.linked_artifacts = await exceptions.getLinked_artifacts({
            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.organizations,
        as: 'organization',
        
      },

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


      {
        model: db.artifacts,
        as: 'linked_artifacts',
        required: false,
      },


    ];

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

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

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

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

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

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

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

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

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

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

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

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


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

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

      


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

        include = [
          {
            model: db.artifacts,
            as: 'linked_artifacts_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  artifact_name: {
                    [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,
                        },
                    };
                }
            }
        }
        

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

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

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

    
};

