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

export async function GET() {
  const software = await prisma.software.findMany({
    include: {
      versions: {
        where: { isLatest: true },
        take: 1,
      },
      _count: { select: { versions: true } },
    },
    orderBy: { updatedAt: "desc" },
  });
  return NextResponse.json(software);
}

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

  const { name, slug, description } = await request.json();

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

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

  const software = await prisma.software.create({
    data: { name, slug, description: description || "" },
  });

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