import dbConnect from "@/database/dbConnect";
import { NextResponse } from "next/server";
import memberModel from "@/database/models/memberModel";
import serviceModel from "@/database/models/serviceModel";
import { Types } from 'mongoose';

// set the revalidate variable
export const revalidate = 5;

/**
 * GET METHOD - Fetch services with their active subscription counts
 * This endpoint calculates real-time active subscriptions for each service
 * by counting members who have active subscriptions to each service
 */
export async function GET(req: Request) {
    try {
        await dbConnect();
        
        const currentUnix = Math.floor(new Date().getTime() / 1000);
        
        // Get all services
        const services = await serviceModel.find({}, { _id: 1, name: 1, status: 1 });
        
        // Calculate active subscriptions for each service
        const servicesWithSubscriptions = await Promise.all(
            services.map(async (service) => {
                // Count members with active subscriptions to this specific service
                const activeSubscriptionsCount = await memberModel.countDocuments({
                    'services': {
                        $elemMatch: {
                            'serviceID': service._id.toString(),
                            'planExpAt_unix': { $gt: currentUnix },
                            'active': true
                        }
                    }
                });
                
                // Count total subscriptions (including expired) for this service
                const totalSubscriptionsCount = await memberModel.countDocuments({
                    'services': {
                        $elemMatch: {
                            'serviceID': service._id.toString()
                        }
                    }
                });
                
                return {
                    _id: service._id,
                    name: service.name,
                    status: service.status,
                    activeSubscriptions: activeSubscriptionsCount,
                    totalSubscriptions: totalSubscriptionsCount,
                    expiredSubscriptions: totalSubscriptionsCount - activeSubscriptionsCount
                };
            })
        );
        
        // Calculate summary statistics
        const totalActiveSubscriptions = servicesWithSubscriptions.reduce(
            (sum, service) => sum + service.activeSubscriptions, 0
        );
        const totalExpiredSubscriptions = servicesWithSubscriptions.reduce(
            (sum, service) => sum + service.expiredSubscriptions, 0
        );
        const totalSubscriptions = servicesWithSubscriptions.reduce(
            (sum, service) => sum + service.totalSubscriptions, 0
        );
        
        // Prepare response data
        const responseData = {
            services: servicesWithSubscriptions,
            summary: {
                totalServices: services.length,
                activeServices: services.filter(s => s.status === 'active').length,
                inactiveServices: services.filter(s => s.status === 'inactive').length,
                totalActiveSubscriptions,
                totalExpiredSubscriptions,
                totalSubscriptions
            }
        };
        
        return NextResponse.json({
            success: true,
            message: "Services subscriptions data retrieved successfully",
            data: responseData,
        }, {
            status: 200,
            headers: {
                "content-type": "application/json"
            }
        });
        
    } catch (error) {
        console.error("Error fetching services subscriptions data:", error);
        return NextResponse.json({
            success: false,
            message: "Server error",
        }, {
            status: 500,
            headers: {
                "content-type": "application/json"
            }
        });
    }
}