import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { readFile, stat } from "fs/promises";
import path from "path";

const LAUNCHER_SLUG = "nanami-launcher";

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const infoOnly = searchParams.get("info") === "1";

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

  if (!software || software.versions.length === 0) {
    if (infoOnly) {
      return NextResponse.json({ available: false });
    }
    return NextResponse.json(
      { error: "暂无可下载版本" },
      { status: 404 }
    );
  }

  const latest = software.versions[0];

  if (infoOnly) {
    const downloadUrl =
      latest.downloadType === "url" && latest.externalUrl
        ? latest.externalUrl
        : `/api/software/download/${latest.id}`;
    return NextResponse.json({
      available: true,
      version: latest.version,
      versionCode: latest.versionCode,
      changelog: latest.changelog,
      fileSize: latest.fileSize,
      createdAt: latest.createdAt,
      downloadUrl,
      downloadType: latest.downloadType,
    });
  }

  await prisma.softwareVersion.update({
    where: { id: latest.id },
    data: { downloadCount: { increment: 1 } },
  });

  if (latest.downloadType === "url" && latest.externalUrl) {
    return new Response(null, {
      status: 302,
      headers: { Location: latest.externalUrl },
    });
  }

  if (latest.filePath) {
    const filePath = path.join(process.cwd(), latest.filePath);
    try {
      await stat(filePath);
    } catch {
      return NextResponse.json({ error: "文件不存在" }, { status: 404 });
    }

    const fileBuffer = await readFile(filePath);
    const ext = path.extname(latest.filePath);
    const fileName = `nanami-launcher-v${latest.version}${ext}`;

    return new NextResponse(fileBuffer, {
      headers: {
        "Content-Type": "application/octet-stream",
        "Content-Disposition": `attachment; filename="${fileName}"`,
        "Content-Length": fileBuffer.length.toString(),
      },
    });
  }

  return NextResponse.json({ error: "无下载来源" }, { status: 404 });
}
