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

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const category = searchParams.get("category");
  const search = searchParams.get("search");
  const publishedOnly = searchParams.get("published") !== "false";

  const where: Record<string, unknown> = {};
  if (publishedOnly) where.published = true;
  if (category) where.category = category;
  if (search) {
    where.OR = [
      { name: { contains: search, mode: "insensitive" } },
      { summary: { contains: search, mode: "insensitive" } },
    ];
  }

  const addons = await prisma.addon.findMany({
    where,
    include: {
      releases: {
        where: { isLatest: true },
        take: 1,
      },
      _count: { select: { releases: true } },
    },
    orderBy: { updatedAt: "desc" },
  });

  return NextResponse.json(addons);
}

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

  const body = await request.json();
  const { name, slug, summary, description, iconUrl, category } = body;

  if (!name || !slug || !summary) {
    return NextResponse.json(
      { error: "name, slug, summary are required" },
      { status: 400 }
    );
  }

  const existing = await prisma.addon.findUnique({ where: { slug } });
  if (existing) {
    return NextResponse.json(
      { error: "Slug already exists" },
      { status: 409 }
    );
  }

  const addon = await prisma.addon.create({
    data: {
      name,
      slug,
      summary,
      description: description || "",
      iconUrl: iconUrl || null,
      category: category || "general",
    },
  });

  return NextResponse.json(addon, { status: 201 });
}
