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

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

        const submissions = await db.submissions.create(
            {
                id: data.id || undefined,
        
        submission_channel: data.submission_channel
        ||
        null
            ,
            
        reference_number: data.reference_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        decision_at: data.decision_at
        ||
        null
            ,
            
        decision_type: data.decision_type
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await submissions.setAuthorization_case( data.authorization_case || null, {
            transaction,
        });
        
        await submissions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return submissions;
    }
    

    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 submissionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                submission_channel: item.submission_channel
            ||
            null
            ,
            
                reference_number: item.reference_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                decision_at: item.decision_at
            ||
            null
            ,
            
                decision_type: item.decision_type
            ||
            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 submissions = await db.submissions.bulkCreate(submissionsData, { transaction });

        // For each item created, replace relation files
        

        return submissions;
    }

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


        

        const updatePayload = {};
        
        if (data.submission_channel !== undefined) updatePayload.submission_channel = data.submission_channel;
        
        
        if (data.reference_number !== undefined) updatePayload.reference_number = data.reference_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.decision_at !== undefined) updatePayload.decision_at = data.decision_at;
        
        
        if (data.decision_type !== undefined) updatePayload.decision_type = data.decision_type;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.authorization_case !== undefined) {
            await submissions.setAuthorization_case(
              
              data.authorization_case,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await submissions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return submissions;
    }

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

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

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


        return submissions;
    }

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

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

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

        await submissions.destroy({
            transaction
        });

        return submissions;
    }

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

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

        if (!submissions) {
            return submissions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.submission_events_submission = await submissions.getSubmission_events_submission({
            transaction
        });
        
        
        
        output.denials_submission = await submissions.getDenials_submission({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.authorization_case = await submissions.getAuthorization_case({
            transaction
        });
        
        
        output.organizations = await submissions.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.authorization_cases,
        as: 'authorization_case',
        
        where: filter.authorization_case ? {
          [Op.or]: [
            { id: { [Op.in]: filter.authorization_case.split('|').map(term => Utils.uuid(term)) } },
            {
              site_of_service: {
                [Op.or]: filter.authorization_case.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.reference_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'submissions',
                        'reference_number',
                        filter.reference_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'submissions',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.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.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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

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

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

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

    
};

