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

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

        const recurring_invoice_templates = await db.recurring_invoice_templates.create(
            {
                id: data.id || undefined,
        
        billing_frequency: data.billing_frequency
        ||
        null
            ,
            
        rate: data.rate
        ||
        null
            ,
            
        next_run_date: data.next_run_date
        ||
        null
            ,
            
        last_run_date: data.last_run_date
        ||
        null
            ,
            
        active_flag: data.active_flag
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await recurring_invoice_templates.setCompany( data.company || null, {
            transaction,
        });
        
        await recurring_invoice_templates.setAgreement( data.agreement || null, {
            transaction,
        });
        

        

        

        return recurring_invoice_templates;
    }
    

    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 recurring_invoice_templatesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                billing_frequency: item.billing_frequency
            ||
            null
            ,
            
                rate: item.rate
            ||
            null
            ,
            
                next_run_date: item.next_run_date
            ||
            null
            ,
            
                last_run_date: item.last_run_date
            ||
            null
            ,
            
                active_flag: item.active_flag
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return recurring_invoice_templates;
    }

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


        

        const updatePayload = {};
        
        if (data.billing_frequency !== undefined) updatePayload.billing_frequency = data.billing_frequency;
        
        
        if (data.rate !== undefined) updatePayload.rate = data.rate;
        
        
        if (data.next_run_date !== undefined) updatePayload.next_run_date = data.next_run_date;
        
        
        if (data.last_run_date !== undefined) updatePayload.last_run_date = data.last_run_date;
        
        
        if (data.active_flag !== undefined) updatePayload.active_flag = data.active_flag;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await recurring_invoice_templates.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.agreement !== undefined) {
            await recurring_invoice_templates.setAgreement(
              
              data.agreement,
              
              { transaction }
            );
        }
        

        
        

        

        return recurring_invoice_templates;
    }

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

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

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


        return recurring_invoice_templates;
    }

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

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

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

        await recurring_invoice_templates.destroy({
            transaction
        });

        return recurring_invoice_templates;
    }

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

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

        if (!recurring_invoice_templates) {
            return recurring_invoice_templates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await recurring_invoice_templates.getCompany({
            transaction
        });
        
        
        output.agreement = await recurring_invoice_templates.getAgreement({
            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 userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.companies,
        as: 'company',
        
      },

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.billing_frequency) {
                where = {
                    ...where,
                billing_frequency: filter.billing_frequency,
            };
            }
            
            if (filter.active_flag) {
                where = {
                    ...where,
                active_flag: filter.active_flag,
            };
            }
            


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

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

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

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

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

    
};

