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

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

        const appeals = await db.appeals.create(
            {
                id: data.id || undefined,
        
        appeal_level: data.appeal_level
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        decision_at: data.decision_at
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
        appeal_summary: data.appeal_summary
        ||
        null
            ,
            
        export_artifact_key: data.export_artifact_key
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await appeals.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await appeals.setLocation( data.location || null, {
            transaction,
        });
        
        await appeals.setDenial( data.denial || null, {
            transaction,
        });
        
        await appeals.setTemplate( data.template || null, {
            transaction,
        });
        
        await appeals.setReviewed_by_user( data.reviewed_by_user || null, {
            transaction,
        });
        

        

        

        return appeals;
    }
    

    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 appealsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                appeal_level: item.appeal_level
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                decision_at: item.decision_at
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
                appeal_summary: item.appeal_summary
            ||
            null
            ,
            
                export_artifact_key: item.export_artifact_key
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return appeals;
    }

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


        

        const updatePayload = {};
        
        if (data.appeal_level !== undefined) updatePayload.appeal_level = data.appeal_level;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.decision_at !== undefined) updatePayload.decision_at = data.decision_at;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        if (data.appeal_summary !== undefined) updatePayload.appeal_summary = data.appeal_summary;
        
        
        if (data.export_artifact_key !== undefined) updatePayload.export_artifact_key = data.export_artifact_key;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await appeals.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await appeals.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.denial !== undefined) {
            await appeals.setDenial(
              
              data.denial,
              
              { transaction }
            );
        }
        
        if (data.template !== undefined) {
            await appeals.setTemplate(
              
              data.template,
              
              { transaction }
            );
        }
        
        if (data.reviewed_by_user !== undefined) {
            await appeals.setReviewed_by_user(
              
              data.reviewed_by_user,
              
              { transaction }
            );
        }
        

        
        

        

        return appeals;
    }

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

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

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


        return appeals;
    }

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

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

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

        await appeals.destroy({
            transaction
        });

        return appeals;
    }

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

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

        if (!appeals) {
            return appeals;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await appeals.getOrganization({
            transaction
        });
        
        
        output.location = await appeals.getLocation({
            transaction
        });
        
        
        output.denial = await appeals.getDenial({
            transaction
        });
        
        
        output.template = await appeals.getTemplate({
            transaction
        });
        
        
        output.reviewed_by_user = await appeals.getReviewed_by_user({
            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.locations,
        as: 'location',
        
        where: filter.location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.location.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

            
            if (filter.appeal_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'appeals',
                        'appeal_summary',
                        filter.appeal_summary,
                    ),
                };
            }
            
            if (filter.export_artifact_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'appeals',
                        'export_artifact_key',
                        filter.export_artifact_key,
                    ),
                };
            }
            

            
            

            
            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.submitted_atRange) {
                const [start, end] = filter.submitted_atRange;

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

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

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

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

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

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

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

            
            if (filter.appeal_level) {
                where = {
                    ...where,
                appeal_level: filter.appeal_level,
            };
            }
            
            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.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.appeals.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(
                        'appeals',
                        'appeal_summary',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

