import { isNull } from "../../helpers/IsNull";
import { PlansAdapterMongoose } from "./Plans.Adapter.Mongoose";
import { FindPlansParams, IPlan, IPlansManager } from "./Plans.interface";

class PlansManager implements IPlansManager {
    plans: PlansAdapterMongoose;

    constructor() {
        this.plans = new PlansAdapterMongoose();
    }

    private getOnePlan(plan: IPlan): IPlan {
        return {
            id: isNull<string>(plan.id, ""),
            name: isNull<string>(plan.name, ""),
            description: isNull<string>(plan.description, ""),
            features: plan.features,
            code: isNull<string>(plan.code, ""),
            price: isNull<number>(plan.price, 0),
            annualPrice: isNull<number>(plan.annualPrice, 0),
            limitOrganizations: isNull<number>(plan.limitOrganizations, 1),
            limitEmployees: isNull<number>(plan.limitEmployees, 1),
            limitServices: isNull<number>(plan.limitServices, 1),
            limitAppointments: isNull<number>(plan.limitAppointments, 1),
            limitClients: isNull<number>(plan.limitClients, 1),
            limitRepeats: isNull<number>(plan.limitRepeats, 1),
            mailNotifications: isNull<boolean>(plan.mailNotifications, false),
            smsNotifications: isNull<boolean>(plan.smsNotifications, false),
            wapNotifications: isNull<boolean>(plan.wapNotifications, false),
            bot: isNull<boolean>(plan.bot, false),
            active: isNull<boolean>(plan.active, false),
            dateLimit: isNull<boolean>(plan.dateLimit, false),
            mpPlanId: isNull<string>(plan.mpPlanId, ""),
            payments: isNull<boolean>(plan.payments, false),
            discount3Months: plan.discount3Months,
            discount6Months: plan.discount6Months,
            discount12Months: plan.discount12Months,
            featured: plan.featured,
        };
    }

    public async find(data: FindPlansParams): Promise<IPlan[]> {
        const plans = await this.plans.find(data);
        const returnPlans: IPlan[] = [];

        for (const plan of plans) {
            returnPlans.push(this.getOnePlan(plan));
        }

        return returnPlans;
    }

    public async findOne(data: FindPlansParams): Promise<IPlan> {
        const plan = await this.plans.findOne(data);

        if (!plan) {
            throw new Error("No se ha encontrado el plan");
        }

        return this.getOnePlan(plan);
    }
}

const PlansList = new PlansManager();

export default PlansList;
