import { NextResponse } from "next/server"
import { eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { profiles } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { stripe } from "@/lib/stripe/client"
import { PLAN_PRICES } from "@/lib/stripe/plans"
import { resolvePriceId } from "@/lib/stripe/prices"

export async function POST(request: Request) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const { plan, interval } = await request.json() as {
    plan: string
    interval?: "month" | "year"
  }

  const planConfig = PLAN_PRICES[plan]
  if (!planConfig) return NextResponse.json({ error: "Invalid plan" }, { status: 400 })

  const billingInterval = interval === "year" ? "year" : "month"
  const priceId = await resolvePriceId(planConfig.plan, billingInterval)
  if (!priceId) {
    return NextResponse.json({ error: "Could not resolve the plan price. Check STRIPE_SECRET_KEY." }, { status: 400 })
  }

  const profile = await db.query.profiles.findFirst({
    where: eq(profiles.id, user.id),
    columns: { stripe_customer_id: true, email: true, full_name: true },
  })

  // Get or create Stripe customer
  let customerId = profile?.stripe_customer_id

  if (!customerId) {
    const customer = await stripe.customers.create({
      email: profile?.email ?? user.email,
      name: profile?.full_name ?? undefined,
      metadata: { user_id: user.id },
    })
    customerId = customer.id

    await db
      .update(profiles)
      .set({ stripe_customer_id: customerId })
      .where(eq(profiles.id, user.id))
  }

  const isLifetime = planConfig.interval === "one_time"
  const appUrl = process.env.NEXT_PUBLIC_APP_URL!

  const session = await stripe.checkout.sessions.create({
    customer: customerId,
    mode: isLifetime ? "payment" : "subscription",
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: `${appUrl}/settings/billing?success=true`,
    cancel_url: `${appUrl}/settings/billing?canceled=true`,
    metadata: {
      user_id: user.id,
      plan: planConfig.plan,
    },
    ...(isLifetime ? {} : {
      subscription_data: {
        metadata: { user_id: user.id, plan: planConfig.plan },
      },
    }),
  })

  return NextResponse.json({ url: session.url })
}
