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

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

        const rate_plans = await db.rate_plans.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        pricing_model: data.pricing_model
        ||
        null
            ,
            
        base_rate: data.base_rate
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        included_km_per_day: data.included_km_per_day
        ||
        null
            ,
            
        extra_km_fee: data.extra_km_fee
        ||
        null
            ,
            
        deposit_amount: data.deposit_amount
        ||
        null
            ,
            
        requires_deposit: data.requires_deposit
        ||
        false
        
            ,
            
        terms: data.terms
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await rate_plans.setCompany( data.company || null, {
            transaction,
        });
        
        await rate_plans.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return rate_plans;
    }
    

    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 rate_plansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                pricing_model: item.pricing_model
            ||
            null
            ,
            
                base_rate: item.base_rate
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                included_km_per_day: item.included_km_per_day
            ||
            null
            ,
            
                extra_km_fee: item.extra_km_fee
            ||
            null
            ,
            
                deposit_amount: item.deposit_amount
            ||
            null
            ,
            
                requires_deposit: item.requires_deposit
            ||
            false
        
            ,
            
                terms: item.terms
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return rate_plans;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.pricing_model !== undefined) updatePayload.pricing_model = data.pricing_model;
        
        
        if (data.base_rate !== undefined) updatePayload.base_rate = data.base_rate;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.included_km_per_day !== undefined) updatePayload.included_km_per_day = data.included_km_per_day;
        
        
        if (data.extra_km_fee !== undefined) updatePayload.extra_km_fee = data.extra_km_fee;
        
        
        if (data.deposit_amount !== undefined) updatePayload.deposit_amount = data.deposit_amount;
        
        
        if (data.requires_deposit !== undefined) updatePayload.requires_deposit = data.requires_deposit;
        
        
        if (data.terms !== undefined) updatePayload.terms = data.terms;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await rate_plans.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await rate_plans.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return rate_plans;
    }

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

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

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


        return rate_plans;
    }

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

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

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

        await rate_plans.destroy({
            transaction
        });

        return rate_plans;
    }

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

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

        if (!rate_plans) {
            return rate_plans;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.rate_rules_rate_plan = await rate_plans.getRate_rules_rate_plan({
            transaction
        });
        
        
        
        
        
        output.bookings_rate_plan = await rate_plans.getBookings_rate_plan({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await rate_plans.getCompany({
            transaction
        });
        
        
        output.organizations = await rate_plans.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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

            
            if (filter.pricing_model) {
                where = {
                    ...where,
                pricing_model: filter.pricing_model,
            };
            }
            
            if (filter.requires_deposit) {
                where = {
                    ...where,
                requires_deposit: filter.requires_deposit,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

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

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

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

        const records = await db.rate_plans.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,
        }));
    }

    
};

