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

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

        const pricing_plans = await db.pricing_plans.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        plan_type: data.plan_type
        ||
        null
            ,
            
        monthly_tuition: data.monthly_tuition
        ||
        null
            ,
            
        included_summary: data.included_summary
        ||
        null
            ,
            
        includes_dinner: data.includes_dinner
        ||
        false
        
            ,
            
        includes_pickup: data.includes_pickup
        ||
        false
        
            ,
            
        includes_dropoff: data.includes_dropoff
        ||
        false
        
            ,
            
        includes_third_shift: data.includes_third_shift
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await pricing_plans.setCamp_session( data.camp_session || null, {
            transaction,
        });
        

        

        

        return pricing_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 pricing_plansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                plan_type: item.plan_type
            ||
            null
            ,
            
                monthly_tuition: item.monthly_tuition
            ||
            null
            ,
            
                included_summary: item.included_summary
            ||
            null
            ,
            
                includes_dinner: item.includes_dinner
            ||
            false
        
            ,
            
                includes_pickup: item.includes_pickup
            ||
            false
        
            ,
            
                includes_dropoff: item.includes_dropoff
            ||
            false
        
            ,
            
                includes_third_shift: item.includes_third_shift
            ||
            false
        
            ,
            
                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 pricing_plans = await db.pricing_plans.bulkCreate(pricing_plansData, { transaction });

        // For each item created, replace relation files
        

        return pricing_plans;
    }

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

        const pricing_plans = await db.pricing_plans.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.plan_type !== undefined) updatePayload.plan_type = data.plan_type;
        
        
        if (data.monthly_tuition !== undefined) updatePayload.monthly_tuition = data.monthly_tuition;
        
        
        if (data.included_summary !== undefined) updatePayload.included_summary = data.included_summary;
        
        
        if (data.includes_dinner !== undefined) updatePayload.includes_dinner = data.includes_dinner;
        
        
        if (data.includes_pickup !== undefined) updatePayload.includes_pickup = data.includes_pickup;
        
        
        if (data.includes_dropoff !== undefined) updatePayload.includes_dropoff = data.includes_dropoff;
        
        
        if (data.includes_third_shift !== undefined) updatePayload.includes_third_shift = data.includes_third_shift;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.camp_session !== undefined) {
            await pricing_plans.setCamp_session(
              
              data.camp_session,
              
              { transaction }
            );
        }
        

        
        

        

        return pricing_plans;
    }

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

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

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


        return pricing_plans;
    }

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

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

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

        await pricing_plans.destroy({
            transaction
        });

        return pricing_plans;
    }

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

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

        if (!pricing_plans) {
            return pricing_plans;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.enrollments_pricing_plan = await pricing_plans.getEnrollments_pricing_plan({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.camp_session = await pricing_plans.getCamp_session({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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



    ];

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

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

            
            

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

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

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

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

            
            if (filter.plan_type) {
                where = {
                    ...where,
                plan_type: filter.plan_type,
            };
            }
            
            if (filter.includes_dinner) {
                where = {
                    ...where,
                includes_dinner: filter.includes_dinner,
            };
            }
            
            if (filter.includes_pickup) {
                where = {
                    ...where,
                includes_pickup: filter.includes_pickup,
            };
            }
            
            if (filter.includes_dropoff) {
                where = {
                    ...where,
                includes_dropoff: filter.includes_dropoff,
            };
            }
            
            if (filter.includes_third_shift) {
                where = {
                    ...where,
                includes_third_shift: filter.includes_third_shift,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.pricing_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'pricing_plans',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

    
};

