import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth } from "@/lib/auth";
import { PREMIUM_PRICES } from "@/lib/tiers";

export async function POST(req: NextRequest) {
  const jwtPayload = await requireAuth(req);
  if (!jwtPayload) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const { priceId } = body;

    if (!priceId) {
      return NextResponse.json(
        { error: "priceId is required" },
        { status: 400 }
      );
    }

    // Determine which tier this priceId maps to
    let tier: "premium" | "pro" | null = null;
    for (const [key, val] of Object.entries(PREMIUM_PRICES)) {
      if (val.priceId === priceId) {
        tier = key as "premium" | "pro";
        break;
      }
    }

    if (!tier) {
      return NextResponse.json(
        { error: "Invalid priceId" },
        { status: 400 }
      );
    }

    // Check if user already has this tier (or higher)
    const user = await prisma.user.findUnique({
      where: { id: jwtPayload.userId },
    });

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

    if (tier === "pro" && user.isPro) {
      return NextResponse.json(
        { error: "You are already a Pro member" },
        { status: 400 }
      );
    }

    if (tier === "premium" && (user.isPremium || user.isPro)) {
      return NextResponse.json(
        { error: "You already have Premium or higher" },
        { status: 400 }
      );
    }

    // In production, this would create a Polar.sh checkout session.
    // For development, we mock the flow by marking the user as premium/pro.
    const useMock = process.env.MOCK_PAYMENTS === "true"
      && process.env.NODE_ENV !== "production";

    if (useMock) {
      const trialEndsAt = new Date();
      trialEndsAt.setDate(trialEndsAt.getDate() + 7);

      const updateData: Record<string, unknown> = {
        trialEndsAt,
      };

      if (tier === "pro") {
        updateData.isPro = true;
      } else {
        updateData.isPremium = true;
      }

      await prisma.user.update({
        where: { id: jwtPayload.userId },
        data: updateData,
      });

      return NextResponse.json({
        success: true,
        url: `/upgrade?upgrade=success&tier=${tier}`,
        mock: true,
        tier,
      });
    }

    // Production path — would create a real Polar checkout session
    // const polarSession = await createPolarCheckout({ priceId, userId: jwtPayload.userId });

    return NextResponse.json({
      success: true,
      url: `/upgrade?upgrade=success&tier=${tier}`,
      tier,
    });
  } catch (error) {
    console.error("Upgrade checkout error:", error);
    return NextResponse.json(
      { error: "Failed to create checkout" },
      { status: 500 }
    );
  }
}
