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

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

  const { id: softwareId } = await params;
  const body = await request.json();
  const {
    version,
    versionCode,
    changelog,
    downloadType,
    filePath,
    externalUrl,
    fileSize,
    forceUpdate,
    minVersion,
  } = body;

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

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

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

  const sv = await prisma.softwareVersion.create({
    data: {
      softwareId,
      version,
      versionCode: Number(versionCode),
      changelog: changelog || "",
      downloadType: downloadType || "local",
      filePath: filePath || null,
      externalUrl: externalUrl || null,
      fileSize: Number(fileSize) || 0,
      forceUpdate: forceUpdate || false,
      minVersion: minVersion || null,
      isLatest: true,
    },
  });

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