import { NextRequest, NextResponse } from "next/server";
import { getStripePriceId } from "@/lib/stripe-prices";
import { logger } from "@/lib/logger";
import {
  CheckoutErrorCode,
  createCheckoutError,
} from "@/lib/errors/checkout-errors";

export const dynamic = "force-dynamic";

// Allowed currencies for checkout
// CRITICAL: Only QAR is supported until multi-currency Stripe products are configured
const ALLOWED_CURRENCIES = ["QAR"];

export async function GET(request: NextRequest) {
  const requestId = `price_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  const requestLogger = logger.scope(`stripe-price:${requestId}`);

  try {
    const { searchParams } = new URL(request.url);
    const tier = searchParams.get("tier");
    const period = searchParams.get("period");
    const currencyParam = searchParams.get("currency") || "QAR";

    // Normalize and validate currency
    const currency = currencyParam.toUpperCase();

    requestLogger.info("Price lookup request", {
      tier,
      period,
      currency,
    });

    // Validate currency
    if (!ALLOWED_CURRENCIES.includes(currency)) {
      requestLogger.warn("Invalid currency requested", {
        currency: currencyParam,
        normalized: currency,
        allowed: ALLOWED_CURRENCIES,
      });

      const error = createCheckoutError(CheckoutErrorCode.INVALID_CURRENCY, {
        currency: currencyParam,
        allowedCurrencies: ALLOWED_CURRENCIES,
        requestId,
      });

      return NextResponse.json(
        {
          error: error.userMessage,
          errorAr: error.userMessageAr,
          code: error.code,
          details: `Currency must be one of: ${ALLOWED_CURRENCIES.join(", ")}`,
          retryable: error.retryable,
          recoverySteps: error.recoverySteps,
          recoveryStepsAr: error.recoveryStepsAr,
        },
        { status: 400 },
      );
    }

    if (!tier || !period) {
      const error = createCheckoutError(CheckoutErrorCode.MISSING_PLAN_DATA, {
        tier,
        period,
        requestId,
      });

      return NextResponse.json(
        {
          error: error.userMessage,
          errorAr: error.userMessageAr,
          code: error.code,
          details: "Missing tier or period parameter",
          retryable: error.retryable,
          recoverySteps: error.recoverySteps,
          recoveryStepsAr: error.recoveryStepsAr,
        },
        { status: 400 },
      );
    }

    if (period !== "monthly" && period !== "yearly") {
      const error = createCheckoutError(
        CheckoutErrorCode.INVALID_BILLING_PERIOD,
        {
          period,
          requestId,
        },
      );

      return NextResponse.json(
        {
          error: error.userMessage,
          errorAr: error.userMessageAr,
          code: error.code,
          details: "Period must be monthly or yearly",
          retryable: error.retryable,
          recoverySteps: error.recoverySteps,
          recoveryStepsAr: error.recoveryStepsAr,
        },
        { status: 400 },
      );
    }

    const priceId = await getStripePriceId(
      tier,
      period as "monthly" | "yearly",
      currency,
    );

    if (!priceId) {
      requestLogger.warn("Price ID not found", {
        tier,
        period,
        currency,
      });

      const error = createCheckoutError(CheckoutErrorCode.PRICE_NOT_FOUND, {
        tier,
        period,
        currency,
        requestId,
      });

      return NextResponse.json(
        {
          error: error.userMessage,
          errorAr: error.userMessageAr,
          code: error.code,
          details: "Price ID not found for tier, period, and currency",
          retryable: error.retryable,
          recoverySteps: error.recoverySteps,
          recoveryStepsAr: error.recoveryStepsAr,
        },
        { status: 404 },
      );
    }

    requestLogger.info("Price ID found", {
      priceId,
      tier,
      period,
      currency,
    });

    return NextResponse.json({
      priceId,
      tier,
      period,
      currency,
      success: true,
    });
  } catch (error) {
    requestLogger.error("Unexpected error in price lookup", error);

    const checkoutError = createCheckoutError(CheckoutErrorCode.UNKNOWN_ERROR, {
      requestId,
      error: error instanceof Error ? error.message : String(error),
    });

    return NextResponse.json(
      {
        error: checkoutError.userMessage,
        errorAr: checkoutError.userMessageAr,
        code: checkoutError.code,
        retryable: checkoutError.retryable,
        recoverySteps: checkoutError.recoverySteps,
        recoveryStepsAr: checkoutError.recoveryStepsAr,
      },
      { status: 500 },
    );
  }
}
