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

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

  const { versionId } = await params;
  const body = await request.json();

  const existing = await prisma.softwareVersion.findUnique({
    where: { id: versionId },
  });
  if (!existing) {
    return NextResponse.json({ error: "Version not found" }, { status: 404 });
  }

  const setLatest = body.isLatest === true && !existing.isLatest;
  if (setLatest) {
    await prisma.softwareVersion.updateMany({
      where: { softwareId: existing.softwareId, isLatest: true },
      data: { isLatest: false },
    });
  }

  const updated = await prisma.softwareVersion.update({
    where: { id: versionId },
    data: {
      ...(body.version !== undefined && { version: body.version }),
      ...(body.versionCode !== undefined && {
        versionCode: Number(body.versionCode),
      }),
      ...(body.changelog !== undefined && { changelog: body.changelog }),
      ...(body.downloadType !== undefined && {
        downloadType: body.downloadType,
      }),
      ...(body.filePath !== undefined && { filePath: body.filePath || null }),
      ...(body.externalUrl !== undefined && {
        externalUrl: body.externalUrl || null,
      }),
      ...(body.fileSize !== undefined && { fileSize: Number(body.fileSize) }),
      ...(body.forceUpdate !== undefined && { forceUpdate: body.forceUpdate }),
      ...(body.minVersion !== undefined && {
        minVersion: body.minVersion || null,
      }),
      ...(body.isLatest !== undefined && { isLatest: body.isLatest }),
    },
  });

  return NextResponse.json(updated);
}

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

  const { versionId } = await params;
  await prisma.softwareVersion.delete({ where: { id: versionId } });
  return NextResponse.json({ success: true });
}
