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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  const addon = await prisma.addon.findFirst({
    where: { OR: [{ id }, { slug: id }] },
    include: {
      releases: { orderBy: { createdAt: "desc" } },
      screenshots: { orderBy: { sortOrder: "asc" } },
    },
  });

  if (!addon) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  return NextResponse.json(addon);
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

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

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

  const addon = await prisma.addon.update({
    where: { id },
    data: {
      ...(name !== undefined && { name }),
      ...(slug !== undefined && { slug }),
      ...(summary !== undefined && { summary }),
      ...(description !== undefined && { description }),
      ...(iconUrl !== undefined && { iconUrl }),
      ...(category !== undefined && { category }),
      ...(published !== undefined && { published }),
    },
  });

  return NextResponse.json(addon);
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;

  await prisma.addon.delete({ where: { id } });

  return NextResponse.json({ success: true });
}
