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

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

        const fee_definitions = await db.fee_definitions.create(
            {
                id: data.id || undefined,
        
        fee_type: data.fee_type
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        allow_installments: data.allow_installments
        ||
        false
        
            ,
            
        minimum_down_payment: data.minimum_down_payment
        ||
        null
            ,
            
        max_installments: data.max_installments
        ||
        null
            ,
            
        installment_deadline: data.installment_deadline
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await fee_definitions.setSchool( data.school || null, {
            transaction,
        });
        
        await fee_definitions.setAcademic_year( data.academic_year || null, {
            transaction,
        });
        
        await fee_definitions.setEducation_level( data.education_level || null, {
            transaction,
        });
        
        await fee_definitions.setClass( data.class || null, {
            transaction,
        });
        

        

        

        return fee_definitions;
    }
    

    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 fee_definitionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                fee_type: item.fee_type
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                allow_installments: item.allow_installments
            ||
            false
        
            ,
            
                minimum_down_payment: item.minimum_down_payment
            ||
            null
            ,
            
                max_installments: item.max_installments
            ||
            null
            ,
            
                installment_deadline: item.installment_deadline
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return fee_definitions;
    }

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


        

        const updatePayload = {};
        
        if (data.fee_type !== undefined) updatePayload.fee_type = data.fee_type;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.allow_installments !== undefined) updatePayload.allow_installments = data.allow_installments;
        
        
        if (data.minimum_down_payment !== undefined) updatePayload.minimum_down_payment = data.minimum_down_payment;
        
        
        if (data.max_installments !== undefined) updatePayload.max_installments = data.max_installments;
        
        
        if (data.installment_deadline !== undefined) updatePayload.installment_deadline = data.installment_deadline;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.school !== undefined) {
            await fee_definitions.setSchool(
              
              data.school,
              
              { transaction }
            );
        }
        
        if (data.academic_year !== undefined) {
            await fee_definitions.setAcademic_year(
              
              data.academic_year,
              
              { transaction }
            );
        }
        
        if (data.education_level !== undefined) {
            await fee_definitions.setEducation_level(
              
              data.education_level,
              
              { transaction }
            );
        }
        
        if (data.class !== undefined) {
            await fee_definitions.setClass(
              
              data.class,
              
              { transaction }
            );
        }
        

        
        

        

        return fee_definitions;
    }

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

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

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


        return fee_definitions;
    }

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

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

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

        await fee_definitions.destroy({
            transaction
        });

        return fee_definitions;
    }

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

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

        if (!fee_definitions) {
            return fee_definitions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.billing_items_fee_definition = await fee_definitions.getBilling_items_fee_definition({
            transaction
        });
        
        
        
        
        
        output.school = await fee_definitions.getSchool({
            transaction
        });
        
        
        output.academic_year = await fee_definitions.getAcademic_year({
            transaction
        });
        
        
        output.education_level = await fee_definitions.getEducation_level({
            transaction
        });
        
        
        output.class = await fee_definitions.getClass({
            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.schools,
        as: 'school',
        
      },

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

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.fee_type) {
                where = {
                    ...where,
                fee_type: filter.fee_type,
            };
            }
            
            if (filter.allow_installments) {
                where = {
                    ...where,
                allow_installments: filter.allow_installments,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            


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

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

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

    
};

