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

const ALLOWED_TIERS = ["tier1", "tier2", "tier3", "tier4", "tier5"];

async function resolveBillableSubscription(userId: string) {
  const directSubscription = await getActiveConvexSubscription(userId);
  if (directSubscription) {
    return directSubscription;
  }

  const orgState = await convexQuery<{
    organization: { ownerId: string };
  }>("organizations/queries:getOrganizationStateByUserId", {
    userId,
  });

  if (
    orgState?.organization?.ownerId &&
    orgState.organization.ownerId !== userId
  ) {
    return await getActiveConvexSubscription(orgState.organization.ownerId);
  }

  return null;
}

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

    const params = request.nextUrl.searchParams;
    const requestedSubscriptionId = params.get("subscriptionId") || "";
    const newTierId = params.get("newTierId") || "";
    const billingPeriodParam = params.get("billingPeriod");
    const billingPeriod: "monthly" | "yearly" =
      billingPeriodParam === "yearly" ? "yearly" : "monthly";
    const currency = (params.get("currency") || "qar").toLowerCase();

    const errors: string[] = [];
    if (!newTierId) errors.push("newTierId is required");
    if (newTierId && !ALLOWED_TIERS.includes(newTierId)) {
      errors.push("newTierId must be tier1-tier5");
    }
    if (!["monthly", "yearly"].includes(billingPeriod)) {
      errors.push("billingPeriod must be monthly or yearly");
    }
    if (currency.length !== 3) {
      errors.push("currency must be a 3-letter code");
    }

    if (errors.length) {
      logger.warn("Upgrade preview validation failed", { errors });
      return NextResponse.json(
        { error: "Invalid request", details: errors },
        { status: 400 },
      );
    }

    const subscription = await resolveBillableSubscription(user.id);
    if (!subscription) {
      logger.warn("Upgrade preview subscription not found", {
        userEmail: user.email,
      });
      return NextResponse.json(
        { error: "Subscription not found" },
        { status: 404 },
      );
    }

    if (
      requestedSubscriptionId &&
      ![
        subscription._id,
        subscription.prismaId,
        subscription.stripeSubscriptionId,
      ]
        .filter(Boolean)
        .includes(requestedSubscriptionId)
    ) {
      return NextResponse.json(
        { error: "Subscription not found" },
        { status: 404 },
      );
    }

    const tierOrder = ["tier1", "tier2", "tier3", "tier4", "tier5"];
    const currentIndex = tierOrder.indexOf(subscription.tierId);
    const nextIndex = tierOrder.indexOf(newTierId);

    if (nextIndex <= currentIndex) {
      return NextResponse.json(
        {
          error: "Invalid upgrade",
          message: "Preview is only available for higher tiers",
        },
        { status: 400 },
      );
    }

    const preview = await previewSubscriptionUpgrade({
      subscriptionId: subscription._id,
      newTierId,
      billingPeriod,
      currency,
    });

    return NextResponse.json({
      success: true,
      ...preview,
    });
  } catch (error) {
    logger.error("Upgrade preview error", {
      error: error instanceof Error ? error.message : "Unknown error",
    });
    return NextResponse.json(
      { error: "Failed to preview upgrade" },
      { status: 500 },
    );
  }
}
