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 addonId = searchParams.get("addonId");

  const where: Record<string, unknown> = {};
  if (addonId) where.addonId = addonId;

  const releases = await prisma.release.findMany({
    where,
    include: { addon: { select: { id: true, name: true, slug: true } } },
    orderBy: { createdAt: "desc" },
  });

  return NextResponse.json(releases);
}

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 {
    addonId,
    version,
    changelog,
    downloadType,
    filePath,
    externalUrl,
    gameVersion,
  } = body;

  if (!addonId || !version) {
    return NextResponse.json(
      { error: "addonId and version are required" },
      { status: 400 }
    );
  }

  if (downloadType === "url" && !externalUrl) {
    return NextResponse.json(
      { error: "externalUrl is required for url type" },
      { status: 400 }
    );
  }

  const addon = await prisma.addon.findUnique({ where: { id: addonId } });
  if (!addon) {
    return NextResponse.json({ error: "Addon not found" }, { status: 404 });
  }

  await prisma.release.updateMany({
    where: { addonId, isLatest: true },
    data: { isLatest: false },
  });

  const release = await prisma.release.create({
    data: {
      addonId,
      version,
      changelog: changelog || "",
      downloadType: downloadType || "local",
      filePath: filePath || null,
      externalUrl: externalUrl || null,
      gameVersion: gameVersion || "",
      isLatest: true,
    },
  });

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