import { NextResponse } from "next/server";
import { db, users, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";

export async function GET() {
  const { session, response } = await requireSession();
  if (response) return response;

  const [dbUser] = await db
    .select({
      tier: users.tier,
      subscriptionStatus: users.subscriptionStatus,
      currentPeriodEnd: users.currentPeriodEnd,
      stripeCustomerId: users.stripeCustomerId,
    })
    .from(users)
    .where(eq(users.id, session!.user.id))
    .limit(1);

  return NextResponse.json({
    tier: dbUser?.tier ?? "free",
    subscriptionStatus: dbUser?.subscriptionStatus ?? null,
    currentPeriodEnd: dbUser?.currentPeriodEnd?.toISOString() ?? null,
    hasStripeCustomer: !!dbUser?.stripeCustomerId,
  });
}
