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

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const slug = searchParams.get("slug");
  const currentVersionCode = searchParams.get("versionCode");

  if (!slug) {
    return NextResponse.json(
      { error: "slug parameter is required" },
      { status: 400 }
    );
  }

  const software = await prisma.software.findUnique({
    where: { slug },
    include: {
      versions: {
        where: { isLatest: true },
        take: 1,
      },
    },
  });

  if (!software || software.versions.length === 0) {
    return NextResponse.json(
      { error: "Software or latest version not found" },
      { status: 404 }
    );
  }

  const latest = software.versions[0];
  const clientVersionCode = currentVersionCode
    ? parseInt(currentVersionCode, 10)
    : 0;

  const hasUpdate = latest.versionCode > clientVersionCode;

  const downloadUrl = latest.downloadType === "url" && latest.externalUrl
    ? latest.externalUrl
    : `${request.nextUrl.origin}/api/software/download/${latest.id}`;

  return NextResponse.json({
    hasUpdate,
    forceUpdate: hasUpdate && latest.forceUpdate,
    latest: {
      version: latest.version,
      versionCode: latest.versionCode,
      changelog: latest.changelog,
      downloadUrl,
      fileSize: latest.fileSize,
      minVersion: latest.minVersion,
      createdAt: latest.createdAt,
    },
  });
}
