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

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

        const billing_items = await db.billing_items.create(
            {
                id: data.id || undefined,
        
        bill_number: data.bill_number
        ||
        null
            ,
            
        period_type: data.period_type
        ||
        null
            ,
            
        period_year: data.period_year
        ||
        null
            ,
            
        period_month: data.period_month
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        amount_total: data.amount_total
        ||
        null
            ,
            
        amount_paid: data.amount_paid
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await billing_items.setFee_definition( data.fee_definition || null, {
            transaction,
        });
        
        await billing_items.setStudent( data.student || null, {
            transaction,
        });
        
        await billing_items.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return billing_items;
    }
    

    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 billing_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                bill_number: item.bill_number
            ||
            null
            ,
            
                period_type: item.period_type
            ||
            null
            ,
            
                period_year: item.period_year
            ||
            null
            ,
            
                period_month: item.period_month
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                amount_total: item.amount_total
            ||
            null
            ,
            
                amount_paid: item.amount_paid
            ||
            null
            ,
            
                status: item.status
            ||
            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 billing_items = await db.billing_items.bulkCreate(billing_itemsData, { transaction });

        // For each item created, replace relation files
        

        return billing_items;
    }

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


        

        const updatePayload = {};
        
        if (data.bill_number !== undefined) updatePayload.bill_number = data.bill_number;
        
        
        if (data.period_type !== undefined) updatePayload.period_type = data.period_type;
        
        
        if (data.period_year !== undefined) updatePayload.period_year = data.period_year;
        
        
        if (data.period_month !== undefined) updatePayload.period_month = data.period_month;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.amount_total !== undefined) updatePayload.amount_total = data.amount_total;
        
        
        if (data.amount_paid !== undefined) updatePayload.amount_paid = data.amount_paid;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.fee_definition !== undefined) {
            await billing_items.setFee_definition(
              
              data.fee_definition,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await billing_items.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await billing_items.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return billing_items;
    }

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

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

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


        return billing_items;
    }

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

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

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

        await billing_items.destroy({
            transaction
        });

        return billing_items;
    }

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

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

        if (!billing_items) {
            return billing_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payments_billing_item = await billing_items.getPayments_billing_item({
            transaction
        });
        
        
        
        
        output.fee_definition = await billing_items.getFee_definition({
            transaction
        });
        
        
        output.student = await billing_items.getStudent({
            transaction
        });
        
        
        output.schools = await billing_items.getSchools({
            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.fee_definitions,
        as: 'fee_definition',
        
        where: filter.fee_definition ? {
          [Op.or]: [
            { id: { [Op.in]: filter.fee_definition.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.fee_definition.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    issued_at: {
                    ...where.issued_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.amount_totalRange) {
                const [start, end] = filter.amount_totalRange;

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

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

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

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

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

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


      

      

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

        where = {
          ...where,
          schoolsId: {[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.billing_items.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(
                        'billing_items',
                        'bill_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

