/**
 * GET /api/user/package-status
 *
 * Returns user's package information including:
 * 1. Selected package (from User.selectedPackage - package intent)
 * 2. Active subscription (from subscriptions table - paid subscription)
 * 3. Payment status (whether user needs to complete payment)
 *
 * This endpoint handles users at ANY stage of signup:
 * - User selected package but hasn't paid -> Show selected package + payment CTA
 * - User has active subscription -> Show subscription details
 * - User has neither -> Prompt to select package
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedEmail } from "@/lib/utils/auth-helpers.util";
import { convexQuery } from "@/lib/convex-client";
import { logger } from "@/lib/logger";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

export async function GET(request: NextRequest) {
  try {
    // Authenticate user - supports both NextAuth and OTP auth_token
    const userEmail = await getAuthenticatedEmail(request, auth);
    if (!userEmail) {
      logger.warn("Unauthorized package status request");
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const rawUser = await convexQuery<Record<string, unknown>>(
      "auth/queries:getUserByEmail",
      {
        email: user.email,
      },
    );
    const subscription = await convexQuery<Record<string, unknown> | null>(
      "billing/queries:getSubscription",
      { userId: user.id },
    );

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

    // Get active subscription from Convex billing (returns first active/trialing)
    const activeSubscription = await convexQuery<ConvexSubscription>(
      "billing/queries:getSubscription",
      {
        userId: user._id,
      },
    );

    // Determine status
    const hasActiveSubscription = !!activeSubscription;
    const hasSelectedPackage = !!user.selectedPackage;

    // Build response based on user's status
    const response: Record<string, unknown> = {
      user: {
        id: user._id,
        email: user.email,
        name: user.name,
        companyName: user.companyName,
      },
      packageStatus: "none", // Default
      selectedPackage: user.selectedPackage,
      goals: user.goals,
    };

    if (hasActiveSubscription && activeSubscription) {
      response.packageStatus = "active";
      response.subscription = {
        id: activeSubscription._id,
        tierId: activeSubscription.tierId,
        status: activeSubscription.status,
        billingPeriod: activeSubscription.billingPeriod,
        currentPeriodEnd: activeSubscription.currentPeriodEnd,
        trialEndsAt: activeSubscription.trialEndsAt,
        setupFeePaid: activeSubscription.setupFeePaid,
        setupFeeAmount: activeSubscription.setupFeeAmount,
        setupFeePaidAt: activeSubscription.setupFeePaidAt,
        paymentMethod:
          activeSubscription.cardBrand && activeSubscription.cardLastFour
            ? {
                brand: activeSubscription.cardBrand,
                lastFour: activeSubscription.cardLastFour,
                id: activeSubscription.paymentMethodId,
              }
            : null,
        stripeCustomerId: activeSubscription.stripeCustomerId,
        stripeSubscriptionId: activeSubscription.stripeSubscriptionId,
        cancelAtPeriodEnd: activeSubscription.cancelAtPeriodEnd,
        cancelledAt: activeSubscription.cancelledAt,
        lastPaymentDate: activeSubscription.lastPaymentDate,
        paymentFailureCount: activeSubscription.paymentFailureCount,
      };
      const billingHistory = subscription.stripeCustomerId
        ? await convexQuery<Array<Record<string, unknown>>>(
            "billing/queries:getBillingHistory",
            {
              customerId: subscription.stripeCustomerId as string,
              limit: 20,
            },
          )
        : [];
      response.billingHistory = (billingHistory ?? []).map((item) => ({
        id: item.prismaId ?? 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,
        invoiceId: item.invoiceId,
      }));
    } else if (hasSelectedPackage) {
      // User selected package but hasn't paid yet
      response.packageStatus = "selected_pending_payment";
      response.message = "Complete payment to activate your subscription";
      response.needsPayment = true;

      // Map package tiers to friendly names
      const tierNames: Record<string, { en: string; ar: string }> = {
        tier1: {
          en: "Starter",
          ar: "\u0627\u0644\u0645\u0628\u062A\u062F\u0626",
        },
        tier2: {
          en: "Professional",
          ar: "\u0627\u0644\u0645\u062D\u062A\u0631\u0641",
        },
        tier3: {
          en: "Business",
          ar: "\u0627\u0644\u0623\u0639\u0645\u0627\u0644",
        },
        tier4: {
          en: "Enterprise",
          ar: "\u0627\u0644\u0645\u0624\u0633\u0633\u0627\u062A",
        },
        tier5: {
          en: "Ultimate",
          ar: "\u0627\u0644\u0645\u062A\u0643\u0627\u0645\u0644\u0629",
        },
      };

      response.packageName = tierNames[user.selectedPackage!] || {
        en: user.selectedPackage,
        ar: user.selectedPackage,
      };
    } else {
      // User hasn't selected any package
      response.packageStatus = "none";
      response.message = "No package selected";
      response.needsPackageSelection = true;
    }

    logger.info("Package status retrieved", {
      userId: user._id,
      packageStatus: response.packageStatus,
      hasSubscription: hasActiveSubscription,
      hasSelectedPackage,
    });

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

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