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

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

        const account_applications = await db.account_applications.create(
            {
                id: data.id || undefined,
        
        requested_role: data.requested_role
        ||
        null
            ,
            
        application_status: data.application_status
        ||
        null
            ,
            
        application_notes: data.application_notes
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await account_applications.setApplicant( data.applicant || null, {
            transaction,
        });
        
        await account_applications.setSchool( data.school || null, {
            transaction,
        });
        
        await account_applications.setReviewed_by( data.reviewed_by || null, {
            transaction,
        });
        

        

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

        return account_applications;
    }
    

    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 account_applicationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                requested_role: item.requested_role
            ||
            null
            ,
            
                application_status: item.application_status
            ||
            null
            ,
            
                application_notes: item.application_notes
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return account_applications;
    }

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


        

        const updatePayload = {};
        
        if (data.requested_role !== undefined) updatePayload.requested_role = data.requested_role;
        
        
        if (data.application_status !== undefined) updatePayload.application_status = data.application_status;
        
        
        if (data.application_notes !== undefined) updatePayload.application_notes = data.application_notes;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.applicant !== undefined) {
            await account_applications.setApplicant(
              
              data.applicant,
              
              { transaction }
            );
        }
        
        if (data.school !== undefined) {
            await account_applications.setSchool(
              
              data.school,
              
              { transaction }
            );
        }
        
        if (data.reviewed_by !== undefined) {
            await account_applications.setReviewed_by(
              
              data.reviewed_by,
              
              { transaction }
            );
        }
        

        
        

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

        return account_applications;
    }

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

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

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


        return account_applications;
    }

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

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

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

        await account_applications.destroy({
            transaction
        });

        return account_applications;
    }

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

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

        if (!account_applications) {
            return account_applications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.applicant = await account_applications.getApplicant({
            transaction
        });
        
        
        output.school = await account_applications.getSchool({
            transaction
        });
        
        
        output.reviewed_by = await account_applications.getReviewed_by({
            transaction
        });
        
        
        output.supporting_documents = await account_applications.getSupporting_documents({
            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 userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.schools,
        as: 'school',
        
      },

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



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

    ];

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

            
            if (filter.application_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'account_applications',
                        'application_notes',
                        filter.application_notes,
                    ),
                };
            }
            

            
            

            
            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.requested_role) {
                where = {
                    ...where,
                requested_role: filter.requested_role,
            };
            }
            
            if (filter.application_status) {
                where = {
                    ...where,
                application_status: filter.application_status,
            };
            }
            


      

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

        where = {
          ...where,
          schoolId: {[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.schoolsId;
        }
        

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

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

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

    
};

