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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  const release = await prisma.release.findUnique({
    where: { id },
    include: { addon: { select: { name: true, slug: true } } },
  });

  if (!release) {
    return NextResponse.json({ error: "Release not found" }, { status: 404 });
  }

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

  await prisma.addon.update({
    where: { id: release.addonId },
    data: { totalDownloads: { increment: 1 } },
  });

  if (release.downloadType === "url" && release.externalUrl) {
    return NextResponse.redirect(release.externalUrl);
  }

  if (release.filePath) {
    const filePath = path.join(process.cwd(), release.filePath);

    try {
      await stat(filePath);
    } catch {
      return NextResponse.json({ error: "File not found" }, { status: 404 });
    }

    const fileBuffer = await readFile(filePath);
    const fileName = `${release.addon.slug}-${release.version}${path.extname(release.filePath)}`;

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

  return NextResponse.json(
    { error: "No download source available" },
    { status: 404 }
  );
}
