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

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

        const agreements = await db.agreements.create(
            {
                id: data.id || undefined,
        
        agreement_number: data.agreement_number
        ||
        null
            ,
            
        agreement_type: data.agreement_type
        ||
        null
            ,
            
        billing_frequency: data.billing_frequency
        ||
        null
            ,
            
        daily_rate: data.daily_rate
        ||
        null
            ,
            
        weekly_rate: data.weekly_rate
        ||
        null
            ,
            
        monthly_rate: data.monthly_rate
        ||
        null
            ,
            
        deposit_required: data.deposit_required
        ||
        false
        
            ,
            
        deposit_amount: data.deposit_amount
        ||
        null
            ,
            
        start_date: data.start_date
        ||
        null
            ,
            
        end_date: data.end_date
        ||
        null
            ,
            
        recurring_invoice_enabled: data.recurring_invoice_enabled
        ||
        false
        
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        created_on: data.created_on
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await agreements.setCompany( data.company || null, {
            transaction,
        });
        
        await agreements.setDriver( data.driver || null, {
            transaction,
        });
        
        await agreements.setVehicle( data.vehicle || null, {
            transaction,
        });
        

        

        

        return agreements;
    }
    

    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 agreementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                agreement_number: item.agreement_number
            ||
            null
            ,
            
                agreement_type: item.agreement_type
            ||
            null
            ,
            
                billing_frequency: item.billing_frequency
            ||
            null
            ,
            
                daily_rate: item.daily_rate
            ||
            null
            ,
            
                weekly_rate: item.weekly_rate
            ||
            null
            ,
            
                monthly_rate: item.monthly_rate
            ||
            null
            ,
            
                deposit_required: item.deposit_required
            ||
            false
        
            ,
            
                deposit_amount: item.deposit_amount
            ||
            null
            ,
            
                start_date: item.start_date
            ||
            null
            ,
            
                end_date: item.end_date
            ||
            null
            ,
            
                recurring_invoice_enabled: item.recurring_invoice_enabled
            ||
            false
        
            ,
            
                status: item.status
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                created_on: item.created_on
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return agreements;
    }

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


        

        const updatePayload = {};
        
        if (data.agreement_number !== undefined) updatePayload.agreement_number = data.agreement_number;
        
        
        if (data.agreement_type !== undefined) updatePayload.agreement_type = data.agreement_type;
        
        
        if (data.billing_frequency !== undefined) updatePayload.billing_frequency = data.billing_frequency;
        
        
        if (data.daily_rate !== undefined) updatePayload.daily_rate = data.daily_rate;
        
        
        if (data.weekly_rate !== undefined) updatePayload.weekly_rate = data.weekly_rate;
        
        
        if (data.monthly_rate !== undefined) updatePayload.monthly_rate = data.monthly_rate;
        
        
        if (data.deposit_required !== undefined) updatePayload.deposit_required = data.deposit_required;
        
        
        if (data.deposit_amount !== undefined) updatePayload.deposit_amount = data.deposit_amount;
        
        
        if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
        
        
        if (data.end_date !== undefined) updatePayload.end_date = data.end_date;
        
        
        if (data.recurring_invoice_enabled !== undefined) updatePayload.recurring_invoice_enabled = data.recurring_invoice_enabled;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await agreements.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.driver !== undefined) {
            await agreements.setDriver(
              
              data.driver,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await agreements.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        

        
        

        

        return agreements;
    }

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

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

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


        return agreements;
    }

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

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

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

        await agreements.destroy({
            transaction
        });

        return agreements;
    }

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

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

        if (!agreements) {
            return agreements;
        }

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

        
        
        
        
        
        
        
        
        output.recurring_invoice_templates_agreement = await agreements.getRecurring_invoice_templates_agreement({
            transaction
        });
        
        
        output.invoices_agreement = await agreements.getInvoices_agreement({
            transaction
        });
        
        
        
        
        
        
        
        
        output.driver_expenses_agreement = await agreements.getDriver_expenses_agreement({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.company = await agreements.getCompany({
            transaction
        });
        
        
        output.driver = await agreements.getDriver({
            transaction
        });
        
        
        output.vehicle = await agreements.getVehicle({
            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.drivers,
        as: 'driver',
        
        where: filter.driver ? {
          [Op.or]: [
            { id: { [Op.in]: filter.driver.split('|').map(term => Utils.uuid(term)) } },
            {
              driver_name: {
                [Op.or]: filter.driver.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_date: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_date: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.agreement_type) {
                where = {
                    ...where,
                agreement_type: filter.agreement_type,
            };
            }
            
            if (filter.billing_frequency) {
                where = {
                    ...where,
                billing_frequency: filter.billing_frequency,
            };
            }
            
            if (filter.deposit_required) {
                where = {
                    ...where,
                deposit_required: filter.deposit_required,
            };
            }
            
            if (filter.recurring_invoice_enabled) {
                where = {
                    ...where,
                recurring_invoice_enabled: filter.recurring_invoice_enabled,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


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

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

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

    
};

