/**
 * DEBUG ENDPOINT - Shows subscription data directly
 * Temporary endpoint to diagnose billing tab issue
 */

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { auth } from "@/lib/auth";

export async function GET(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.email) {
      return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
    }

    // Find user with all subscriptions
    const user = await prisma.users.findUnique({
      where: { email: session.user.email },
      select: {
        id: true,
        email: true,
        name: true,
        selectedPackage: true,
        subscriptions: {
          orderBy: { createdAt: "desc" },
          take: 5, // Get last 5 subscriptions
        },
      },
    });

    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    // Filter active subscriptions
    const activeSubscriptions = user.subscriptions.filter(
      (s) =>
        s.status === "active" ||
        s.status === "trialing" ||
        s.status === "past_due",
    );

    return NextResponse.json({
      debug: true,
      timestamp: new Date().toISOString(),
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        selectedPackage: user.selectedPackage,
      },
      subscriptions: {
        total: user.subscriptions.length,
        active: activeSubscriptions.length,
        all: user.subscriptions.map((s) => ({
          id: s.id,
          status: s.status,
          tierId: s.tierId,
          billingPeriod: s.billingPeriod,
          trialEndsAt: s.trialEndsAt,
          currentPeriodEnd: s.currentPeriodEnd,
          setupFeePaid: s.setupFeePaid,
          setupFeeAmount: s.setupFeeAmount,
          stripeCustomerId: s.stripeCustomerId,
          stripeSubscriptionId: s.stripeSubscriptionId,
          createdAt: s.createdAt,
        })),
        activeList: activeSubscriptions.map((s) => ({
          id: s.id,
          status: s.status,
          tierId: s.tierId,
        })),
      },
      recommendation:
        activeSubscriptions.length > 0
          ? "✅ Active subscription found - should display in billing tab"
          : "❌ No active subscription - user needs to subscribe",
    });
  } catch (error: any) {
    return NextResponse.json(
      {
        error: error.message,
        stack: error.stack,
      },
      { status: 500 },
    );
  }
}
