const UserSubscription = require('../models/UserSubscription');
const PricingPlan = require("../models/SubscriptionPlan");
const UserActivity = require("../models/UserActivity");

module.exports.checkcron = async (req, res) => {
    try {
        const today = new Date();
        // 1. Find users whose plan will expire
        const expiredSubs = await UserSubscription.find({
            status: "active",
            endDate: { $ne: null, $lt: today }
        });

        // 2. Expire them
        await UserSubscription.updateMany(
            {
                _id: { $in: expiredSubs.map(sub => sub._id) }
            },
            {
                $set: { status: "expired" }
            }
        );

        const freePlan = await PricingPlan.findOne({
            monthlyPrice: 0,
            yearlyPrice: 0,
            status: true,
            isFree: true,
        });
        if (freePlan) {

            // 3. Assign FREE plan to those users
            for (const user of expiredSubs) {

                // check if already active plan exists
                const existingSub = await UserSubscription.findOne({
                    userId: user._id,
                    status: "active",
                });

                if (!existingSub) {
                    // Set default values for the free plan (fallback to 0)
                    const websiteLimit = freePlan.monthlyWebsiteLimit || 0;
                    const totalPageLimite = freePlan.maxPages || 0;
                    const totalSectionLimite = freePlan.maxSectionsPerPage || 0;
                    const features = freePlan.features || 0;

                    const subscription = new UserSubscription({
                        userId: user._id,
                        planId: freePlan._id,
                        billingType: "monthly",
                        totalWebsite: websiteLimit,
                        websiteCreated: 0,
                        totalPageLimite: totalPageLimite,
                        totalSectionLimite: totalSectionLimite,
                        features: features,
                        startDate: new Date(),
                        endDate: null,
                        status: "active",
                        isFree: freePlan?.isFree
                    });

                    await subscription.save();

                    // Log activity
                    if (UserActivity) {
                        await UserActivity.create({
                            userId: user._id,
                            action: `✅ ${freePlan?.name} plan activated. Enjoy your new limits!`,
                            target: freePlan._id.toString(),
                            atypes: "plan_active"
                        });
                    }
                }
            }

        }

        // 2. Reset FREE plan usage (monthly)
        const freePlans = await UserSubscription.find({
            status: "active",
            isFree: true
        });

        for (const sub of freePlans) {
            const lastReset = new Date(sub.lastResetDate);

            const isNewMonth =
                lastReset.getMonth() !== today.getMonth() ||
                lastReset.getFullYear() !== today.getFullYear();

            if (isNewMonth) {
                sub.websiteCreated = 0; // 🔥 reset usage
                sub.lastResetDate = today;
                await sub.save();
            }
        }

        res.status(200).json({
            success: true,
            message: "Cron executed"
        });

    } catch (error) {
        console.error("Cron Error:", error);
        res.status(500).json({
            success: false,
            message: "Cron failed"
        });
    }
}
