import { NextRequest, NextResponse } from "next/server";
import { logger } from "@/lib/logger";
import { auth } from "@/lib/auth";
import { getAuthenticatedConvexUser } from "@/lib/convex-auth-state";
import { convexQuery } from "@/lib/convex-client";

/**
 * GET /api/subscription/details
 *
 * Retrieves current user's subscription details including:
 * - Subscription status and tier
 * - Payment method details (card brand, last 4)
 * - Setup fee information
 * - Billing history
 * - Current and next billing dates
 *
 * Response:
 * {
 *   subscription: {
 *     id: string,
 *     tierId: string,
 *     status: string,
 *     billingPeriod: string,
 *     currentPeriodEnd: Date,
 *     trialEndsAt: Date | null,
 *     setupFeePaid: boolean,
 *     setupFeeAmount: number | null,
 *     paymentMethod: {
 *       brand: string,
 *       lastFour: string
 *     } | null
 *   },
 *   billingHistory: Array<{
 *     event: string,
 *     amount: number,
 *     currency: string,
 *     createdAt: Date
 *   }>
 * }
 */

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedConvexUser(request, auth);
    if (!user) {
      logger.warn("Unauthorized subscription details request - no valid auth");
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

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

    if (!result) {
      logger.info("No active subscription found", { userEmail: user.email });
      return NextResponse.json(
        { error: "No active subscription found" },
        { status: 404 },
      );
    }

    const sub = result.subscription;
    const response = {
      subscription: {
        id: sub._id,
        tierId: sub.tierId,
        status: sub.status,
        billingPeriod: sub.billingPeriod,
        currentPeriodEnd: sub.currentPeriodEnd
          ? new Date(sub.currentPeriodEnd as number).toISOString()
          : null,
        trialEndsAt: sub.trialEndsAt
          ? new Date(sub.trialEndsAt as number).toISOString()
          : null,
        setupFeePaid: sub.setupFeePaid,
        setupFeeAmount: sub.setupFeeAmount ?? null,
        setupFeePaidAt: sub.setupFeePaidAt
          ? new Date(sub.setupFeePaidAt as number).toISOString()
          : null,
        paymentMethod:
          sub.cardBrand && sub.cardLastFour
            ? {
                brand: sub.cardBrand,
                lastFour: sub.cardLastFour,
                id: sub.paymentMethodId ?? null,
              }
            : null,
        stripeCustomerId: sub.stripeCustomerId,
        stripeSubscriptionId: sub.stripeSubscriptionId,
        cancelAtPeriodEnd: sub.cancelAtPeriodEnd,
        cancelledAt: sub.cancelledAt
          ? new Date(sub.cancelledAt as number).toISOString()
          : null,
        lastPaymentDate: sub.lastPaymentDate
          ? new Date(sub.lastPaymentDate as number).toISOString()
          : null,
        paymentFailureCount: sub.paymentFailureCount,
      },
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        companyName: user.companyName ?? null,
      },
      billingHistory: result.billingHistory.map((item) => ({
        id: item._id,
        event: item.event,
        amount: item.amount,
        currency: item.currency,
        createdAt: item.createdAt
          ? new Date(item.createdAt as number).toISOString()
          : null,
        metadata: item.metadata ?? null,
        invoiceId: item.invoiceId ?? null,
      })),
    };

    logger.info("Subscription details retrieved", {
      userId: user.id,
      subscriptionId: sub._id,
    });

    return NextResponse.json(response);
  } catch (error) {
    logger.error("Subscription details route error", {
      error: error instanceof Error ? error.message : "Unknown error",
      stack: error instanceof Error ? error.stack : undefined,
    });

    return NextResponse.json(
      { error: "Failed to retrieve subscription details" },
      { status: 500 },
    );
  }
}
