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

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

        const admission_applications = await db.admission_applications.create(
            {
                id: data.id || undefined,
        
        entry_type: data.entry_type
        ||
        null
            ,
            
        applicant_full_name: data.applicant_full_name
        ||
        null
            ,
            
        gender: data.gender
        ||
        null
            ,
            
        date_of_birth: data.date_of_birth
        ||
        null
            ,
            
        previous_school: data.previous_school
        ||
        null
            ,
            
        guardian_full_name: data.guardian_full_name
        ||
        null
            ,
            
        guardian_phone: data.guardian_phone
        ||
        null
            ,
            
        guardian_email: data.guardian_email
        ||
        null
            ,
            
        address_text: data.address_text
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await admission_applications.setRequested_grade( data.requested_grade || null, {
            transaction,
        });
        
        await admission_applications.setRequested_stream( data.requested_stream || null, {
            transaction,
        });
        

        

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

        return admission_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 admission_applicationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                entry_type: item.entry_type
            ||
            null
            ,
            
                applicant_full_name: item.applicant_full_name
            ||
            null
            ,
            
                gender: item.gender
            ||
            null
            ,
            
                date_of_birth: item.date_of_birth
            ||
            null
            ,
            
                previous_school: item.previous_school
            ||
            null
            ,
            
                guardian_full_name: item.guardian_full_name
            ||
            null
            ,
            
                guardian_phone: item.guardian_phone
            ||
            null
            ,
            
                guardian_email: item.guardian_email
            ||
            null
            ,
            
                address_text: item.address_text
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return admission_applications;
    }

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

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


        

        const updatePayload = {};
        
        if (data.entry_type !== undefined) updatePayload.entry_type = data.entry_type;
        
        
        if (data.applicant_full_name !== undefined) updatePayload.applicant_full_name = data.applicant_full_name;
        
        
        if (data.gender !== undefined) updatePayload.gender = data.gender;
        
        
        if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
        
        
        if (data.previous_school !== undefined) updatePayload.previous_school = data.previous_school;
        
        
        if (data.guardian_full_name !== undefined) updatePayload.guardian_full_name = data.guardian_full_name;
        
        
        if (data.guardian_phone !== undefined) updatePayload.guardian_phone = data.guardian_phone;
        
        
        if (data.guardian_email !== undefined) updatePayload.guardian_email = data.guardian_email;
        
        
        if (data.address_text !== undefined) updatePayload.address_text = data.address_text;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requested_grade !== undefined) {
            await admission_applications.setRequested_grade(
              
              data.requested_grade,
              
              { transaction }
            );
        }
        
        if (data.requested_stream !== undefined) {
            await admission_applications.setRequested_stream(
              
              data.requested_stream,
              
              { transaction }
            );
        }
        

        
        

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

        return admission_applications;
    }

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

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

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


        return admission_applications;
    }

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

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

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

        await admission_applications.destroy({
            transaction
        });

        return admission_applications;
    }

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

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

        if (!admission_applications) {
            return admission_applications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requested_grade = await admission_applications.getRequested_grade({
            transaction
        });
        
        
        output.requested_stream = await admission_applications.getRequested_stream({
            transaction
        });
        
        
        output.documents = await admission_applications.getDocuments({
            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.grades,
        as: 'requested_grade',
        
        where: filter.requested_grade ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requested_grade.split('|').map(term => Utils.uuid(term)) } },
            {
              label: {
                [Op.or]: filter.requested_grade.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.applicant_full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admission_applications',
                        'applicant_full_name',
                        filter.applicant_full_name,
                    ),
                };
            }
            
            if (filter.previous_school) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admission_applications',
                        'previous_school',
                        filter.previous_school,
                    ),
                };
            }
            
            if (filter.guardian_full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admission_applications',
                        'guardian_full_name',
                        filter.guardian_full_name,
                    ),
                };
            }
            
            if (filter.guardian_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admission_applications',
                        'guardian_phone',
                        filter.guardian_phone,
                    ),
                };
            }
            
            if (filter.guardian_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admission_applications',
                        'guardian_email',
                        filter.guardian_email,
                    ),
                };
            }
            
            if (filter.address_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'admission_applications',
                        'address_text',
                        filter.address_text,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    date_of_birth: {
                    ...where.date_of_birth,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      



            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.admission_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'admission_applications',
                        'applicant_full_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

