import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

export async function GET(req: NextRequest) {
  const session = await auth();

  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { searchParams } = req.nextUrl;
  const period = searchParams.get("period");
  const provider = searchParams.get("provider");

  // Build where clause
  const where: Record<string, unknown> = { userId: session.user.id };
  if (period) where.period = period;
  if (provider) where.provider = provider;

  try {
    const entries = await db.costEntry.findMany({
      where,
      orderBy: [{ period: "desc" }, { createdAt: "desc" }],
    });

    // Compute totals
    const byProvider: Record<string, number> = {};
    const byMonth: Record<string, number> = {};
    let total = 0;

    for (const entry of entries) {
      byProvider[entry.provider] = (byProvider[entry.provider] || 0) + entry.amount;
      byMonth[entry.period] = (byMonth[entry.period] || 0) + entry.amount;
      total += entry.amount;
    }

    return NextResponse.json({
      entries,
      totals: { byProvider, byMonth, total },
    });
  } catch {
    return NextResponse.json(
      { error: "Failed to fetch cost entries" },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  const session = await auth();

  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const { provider, amount, period, category, note } = body;

    // Validate required fields
    if (!provider || amount === undefined || amount === null || !period) {
      return NextResponse.json(
        { error: "Provider, amount, and period are required" },
        { status: 400 }
      );
    }

    // Validate provider
    const validProviders = ["openai", "anthropic", "google", "aws", "azure", "manual", "other"];
    if (!validProviders.includes(provider)) {
      return NextResponse.json(
        { error: `Invalid provider. Must be one of: ${validProviders.join(", ")}` },
        { status: 400 }
      );
    }

    // Validate amount
    if (typeof amount !== "number" || amount < 0) {
      return NextResponse.json(
        { error: "Amount must be a non-negative number" },
        { status: 400 }
      );
    }

    // Validate period format (YYYY-MM)
    const periodRegex = /^\d{4}-\d{2}$/;
    if (!periodRegex.test(period)) {
      return NextResponse.json(
        { error: "Period must be in YYYY-MM format" },
        { status: 400 }
      );
    }

    // Validate category if provided
    const validCategories = ["api", "subscription", "other"];
    if (category && !validCategories.includes(category)) {
      return NextResponse.json(
        { error: `Invalid category. Must be one of: ${validCategories.join(", ")}` },
        { status: 400 }
      );
    }

    const entry = await db.costEntry.create({
      data: {
        userId: session.user.id,
        provider,
        amount,
        period,
        category: category || "api",
        note: note || null,
      },
    });

    return NextResponse.json({ entry }, { status: 201 });
  } catch {
    return NextResponse.json(
      { error: "Failed to create cost entry" },
      { status: 500 }
    );
  }
}
