import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";
import { getStripe, TIER_CONFIG } from "@/lib/stripe";

export async function POST(request: Request) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { priceId, tierKey } = body as {
      priceId?: string;
      tierKey?: string;
    };

    let resolvedPriceId = priceId;

    if (!resolvedPriceId && tierKey) {
      const tierConfig =
        TIER_CONFIG[tierKey as keyof typeof TIER_CONFIG];
      if (tierConfig && "priceId" in tierConfig) {
        resolvedPriceId = tierConfig.priceId;
      }
    }

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

    const validPriceIds = [TIER_CONFIG.STARTER.priceId, TIER_CONFIG.PRO.priceId];
    if (!validPriceIds.includes(resolvedPriceId)) {
      return NextResponse.json(
        { error: "Invalid priceId" },
        { status: 400 }
      );
    }

    const userId = session.user.id;

    let subscription = await prisma.subscription.findUnique({
      where: { userId },
    });

    let stripeCustomerId = subscription?.stripeCustomerId;

    if (!stripeCustomerId) {
      const customer = await getStripe().customers.create({
        email: session.user.email,
        name: session.user.name ?? undefined,
        metadata: { userId },
      });
      stripeCustomerId = customer.id;

      if (subscription) {
        await prisma.subscription.update({
          where: { userId },
          data: { stripeCustomerId },
        });
      } else {
        subscription = await prisma.subscription.create({
          data: {
            userId,
            stripeCustomerId,
          },
        });
      }
    }

    const ALLOWED_ORIGINS = [
      "https://agentlens.vectry.tech",
      "http://localhost:3000",
    ];
    const requestOrigin = request.headers.get("origin");
    const origin = ALLOWED_ORIGINS.includes(requestOrigin ?? "")
      ? requestOrigin!
      : "https://agentlens.vectry.tech";

    const checkoutSession = await getStripe().checkout.sessions.create({
      customer: stripeCustomerId,
      mode: "subscription",
      line_items: [{ price: resolvedPriceId, quantity: 1 }],
      success_url: `${origin}/dashboard/settings?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${origin}/dashboard/settings`,
      metadata: { userId },
    });

    return NextResponse.json({ url: checkoutSession.url }, { status: 200 });
  } catch (error) {
    console.error("Error creating checkout session:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
