import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { PRICING_TIERS, TIER_MAPPING } from "@/lib/config/pricing-tiers";
import { convexQuery } from "@/lib/convex-client";
export async function GET(request: NextRequest) {
  try {
    // Get current user - supports both NextAuth and OTP auth_token
    const user = await getAuthenticatedUser(request, auth);

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const subscription = await convexQuery<Record<string, unknown>>(
      "billing/queries:getActiveSubscription",
      { userId: user.id },
    );

    if (!subscription) {
      return NextResponse.json(
        { error: "No active subscription", hasSubscription: false },
        { status: 404 },
      );
    }

    const tierId = String(subscription.tierId);
    const billingPeriod = String(subscription.billingPeriod || "monthly");
    const pricingTier = PRICING_TIERS.find((item) => item.id === tierId);

    if (!pricingTier) {
      return NextResponse.json(
        { error: "Subscription tier configuration not found" },
        { status: 500 },
      );
    }

    const currentPeriodEnd = Number(
      subscription.currentPeriodEnd || Date.now(),
    );
    const daysInPeriod = billingPeriod === "yearly" ? 365 : 30;
    const currentPeriodStart =
      currentPeriodEnd - daysInPeriod * 24 * 60 * 60 * 1000;
    const daysRemaining = Math.max(
      0,
      Math.ceil((currentPeriodEnd - Date.now()) / (1000 * 60 * 60 * 24)),
    );
    const daysUsed = Math.max(0, daysInPeriod - daysRemaining);

    return NextResponse.json({
      hasSubscription: true,
      subscription: {
        id: subscription.prismaId ?? subscription._id,
        planType: TIER_MAPPING[tierId as keyof typeof TIER_MAPPING] ?? tierId,
        status: subscription.status,
        currentPeriodStart: new Date(currentPeriodStart).toISOString(),
        currentPeriodEnd: new Date(currentPeriodEnd).toISOString(),
        cancelAtPeriodEnd: Boolean(subscription.cancelAtPeriodEnd),
        amount: getPlanAmountGBP(tierId, billingPeriod),
        currency: "GBP",
        daysRemaining,
        daysInPeriod,
        daysUsed,
        planDetails: {
          type: TIER_MAPPING[tierId as keyof typeof TIER_MAPPING] ?? tierId,
          name: pricingTier.nameEn,
          nameAr: pricingTier.nameAr,
          monthlyPrice: pricingTier.priceGBP,
          features: pricingTier.featuresEn,
          featuresAr: pricingTier.featuresAr,
        },
      },
    });
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : "Unknown error";
    console.error("Error fetching subscription:", error);
    return NextResponse.json(
      { error: "Internal server error", message: error.message },
      { status: 500 },
    );
  }
}
