import { NextRequest, NextResponse } from "next/server";
import { readFile, unlink } from "fs/promises";
import { join } from "path";
import { parseMultipartUpload } from "../parse-upload";
import { requireAuth } from "../auth-check";

/**
 * iLovePDF API integration for PDF compression.
 *
 * Workflow: auth → start → upload → process → download
 * Docs: https://www.iloveapi.com/docs/api-reference
 *
 * Env vars: ILOVEPDF_PUBLIC_KEY
 * Free tier: 250 files/month
 */

const ILOVEPDF_PUBLIC_KEY = process.env.ILOVEPDF_PUBLIC_KEY ?? "";
const API_BASE = "https://api.ilovepdf.com/v1";

async function cleanup(dir: string) {
  try {
    const { readdir, rmdir } = await import("fs/promises");
    const files = await readdir(dir);
    for (const f of files) {
      await unlink(join(dir, f)).catch(() => {});
    }
    await rmdir(dir).catch(() => {});
  } catch {
    // non-critical
  }
}

export async function POST(req: NextRequest) {
  const authError = await requireAuth(req);
  if (authError) return authError;

  if (!ILOVEPDF_PUBLIC_KEY) {
    return NextResponse.json(
      {
        error:
          "iLovePDF nu este configurat. Setează ILOVEPDF_PUBLIC_KEY în variabilele de mediu.",
      },
      { status: 501 },
    );
  }

  let tmpDir = "";
  try {
    // Stream upload to disk — works for any file size
    const upload = await parseMultipartUpload(req);
    tmpDir = upload.tmpDir;

    const originalSize = upload.size;

    if (originalSize < 100) {
      return NextResponse.json(
        { error: "Fișierul PDF este gol sau prea mic." },
        { status: 400 },
      );
    }

    // Compression level from form field
    const levelParam = upload.fields["level"] ?? "";
    const compressionLevel =
      levelParam === "extreme"
        ? "extreme"
        : levelParam === "low"
          ? "low"
          : "recommended";

    // Step 1: Authenticate
    const authRes = await fetch(`${API_BASE}/auth`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ public_key: ILOVEPDF_PUBLIC_KEY }),
    });

    if (!authRes.ok) {
      const text = await authRes.text().catch(() => "");
      return NextResponse.json(
        { error: `iLovePDF auth failed: ${authRes.status} — ${text}` },
        { status: 502 },
      );
    }

    const { token } = (await authRes.json()) as { token: string };

    // Step 2: Start compress task
    const startRes = await fetch(`${API_BASE}/start/compress`, {
      method: "GET",
      headers: { Authorization: `Bearer ${token}` },
    });

    if (!startRes.ok) {
      const text = await startRes.text().catch(() => "");
      return NextResponse.json(
        { error: `iLovePDF start failed: ${startRes.status} — ${text}` },
        { status: 502 },
      );
    }

    const { server, task } = (await startRes.json()) as {
      server: string;
      task: string;
    };

    // Step 3: Upload file (read from disk to avoid double-buffering)
    const fileBuffer = await readFile(upload.filePath);
    const uploadForm = new FormData();
    uploadForm.append("task", task);
    uploadForm.append(
      "file",
      new Blob([new Uint8Array(fileBuffer)], { type: "application/pdf" }),
      upload.filename,
    );

    const uploadRes = await fetch(`https://${server}/v1/upload`, {
      method: "POST",
      headers: { Authorization: `Bearer ${token}` },
      body: uploadForm,
      signal: AbortSignal.timeout(600_000), // 10 min for very large files
    });

    if (!uploadRes.ok) {
      const text = await uploadRes.text().catch(() => "");
      return NextResponse.json(
        { error: `iLovePDF upload failed: ${uploadRes.status} — ${text}` },
        { status: 502 },
      );
    }

    const { server_filename } = (await uploadRes.json()) as {
      server_filename: string;
    };

    // Step 4: Process
    const processRes = await fetch(`https://${server}/v1/process`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        task,
        tool: "compress",
        compression_level: compressionLevel,
        files: [
          {
            server_filename,
            filename: upload.filename,
          },
        ],
      }),
      signal: AbortSignal.timeout(600_000),
    });

    if (!processRes.ok) {
      const text = await processRes.text().catch(() => "");
      return NextResponse.json(
        { error: `iLovePDF process failed: ${processRes.status} — ${text}` },
        { status: 502 },
      );
    }

    // Step 5: Download result
    const downloadRes = await fetch(
      `https://${server}/v1/download/${task}`,
      {
        headers: { Authorization: `Bearer ${token}` },
        signal: AbortSignal.timeout(600_000),
      },
    );

    if (!downloadRes.ok) {
      const text = await downloadRes.text().catch(() => "");
      return NextResponse.json(
        {
          error: `iLovePDF download failed: ${downloadRes.status} — ${text}`,
        },
        { status: 502 },
      );
    }

    const resultBlob = await downloadRes.blob();
    const resultBuffer = Buffer.from(await resultBlob.arrayBuffer());
    const compressedSize = resultBuffer.length;

    // Clean up task on iLovePDF (fire and forget)
    fetch(`https://${server}/v1/task/${task}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${token}` },
    }).catch(() => {});

    return new NextResponse(new Uint8Array(resultBuffer), {
      status: 200,
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="${encodeURIComponent(upload.filename.replace(/\.pdf$/i, "-comprimat.pdf"))}"`,
        "X-Original-Size": String(originalSize),
        "X-Compressed-Size": String(compressedSize),
      },
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json(
      { error: `Eroare iLovePDF: ${message}` },
      { status: 500 },
    );
  } finally {
    if (tmpDir) await cleanup(tmpDir);
  }
}
