import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";

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

    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      select: {
        id: true,
        email: true,
        name: true,
        createdAt: true,
        subscription: {
          select: {
            tier: true,
            status: true,
            sessionsUsed: true,
            sessionsLimit: true,
            currentPeriodStart: true,
            currentPeriodEnd: true,
            stripeCustomerId: true,
          },
        },
      },
    });

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

    // Don't expose raw Stripe customer ID to the client
    const { subscription, ...rest } = user;
    const safeSubscription = subscription
      ? {
          tier: subscription.tier,
          status: subscription.status,
          sessionsUsed: subscription.sessionsUsed,
          sessionsLimit: subscription.sessionsLimit,
          currentPeriodStart: subscription.currentPeriodStart,
          currentPeriodEnd: subscription.currentPeriodEnd,
          hasStripeSubscription: !!subscription.stripeCustomerId,
        }
      : null;

    return NextResponse.json({ ...rest, subscription: safeSubscription }, { status: 200 });
  } catch (error) {
    console.error("Error fetching account:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
