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

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

        const company_subscriptions = await db.company_subscriptions.create(
            {
                id: data.id || undefined,
        
        billing_provider: data.billing_provider
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        current_period_start_at: data.current_period_start_at
        ||
        null
            ,
            
        current_period_end_at: data.current_period_end_at
        ||
        null
            ,
            
        trial_end_at: data.trial_end_at
        ||
        null
            ,
            
        provider_customer_key: data.provider_customer_key
        ||
        null
            ,
            
        provider_subscription_key: data.provider_subscription_key
        ||
        null
            ,
            
        auto_renew: data.auto_renew
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return company_subscriptions;
    }
    

    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 company_subscriptionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                billing_provider: item.billing_provider
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                current_period_start_at: item.current_period_start_at
            ||
            null
            ,
            
                current_period_end_at: item.current_period_end_at
            ||
            null
            ,
            
                trial_end_at: item.trial_end_at
            ||
            null
            ,
            
                provider_customer_key: item.provider_customer_key
            ||
            null
            ,
            
                provider_subscription_key: item.provider_subscription_key
            ||
            null
            ,
            
                auto_renew: item.auto_renew
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return company_subscriptions;
    }

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


        

        const updatePayload = {};
        
        if (data.billing_provider !== undefined) updatePayload.billing_provider = data.billing_provider;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.current_period_start_at !== undefined) updatePayload.current_period_start_at = data.current_period_start_at;
        
        
        if (data.current_period_end_at !== undefined) updatePayload.current_period_end_at = data.current_period_end_at;
        
        
        if (data.trial_end_at !== undefined) updatePayload.trial_end_at = data.trial_end_at;
        
        
        if (data.provider_customer_key !== undefined) updatePayload.provider_customer_key = data.provider_customer_key;
        
        
        if (data.provider_subscription_key !== undefined) updatePayload.provider_subscription_key = data.provider_subscription_key;
        
        
        if (data.auto_renew !== undefined) updatePayload.auto_renew = data.auto_renew;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return company_subscriptions;
    }

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

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

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


        return company_subscriptions;
    }

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

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

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

        await company_subscriptions.destroy({
            transaction
        });

        return company_subscriptions;
    }

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

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

        if (!company_subscriptions) {
            return company_subscriptions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payments_company_subscription = await company_subscriptions.getPayments_company_subscription({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.company = await company_subscriptions.getCompany({
            transaction
        });
        
        
        output.plan = await company_subscriptions.getPlan({
            transaction
        });
        
        
        output.organizations = await company_subscriptions.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)) } },
            {
              company_name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.subscription_plans,
        as: 'plan',
        
        where: filter.plan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.plan.split('|').map(term => Utils.uuid(term)) } },
            {
              plan_name: {
                [Op.or]: filter.plan.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.provider_customer_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_subscriptions',
                        'provider_customer_key',
                        filter.provider_customer_key,
                    ),
                };
            }
            
            if (filter.provider_subscription_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_subscriptions',
                        'provider_subscription_key',
                        filter.provider_subscription_key,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

      

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

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

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

    
};

