import { NextRequest, NextResponse } from "next/server";
import { exec } from "child_process";
import { promisify } from "util";
import { writeFile, unlink, readFile } from "fs/promises";
import { tmpdir } from "os";
import { join } from "path";
import { randomBytes } from "crypto";

const execAsync = promisify(exec);

export async function POST(req: NextRequest) {
  const { pem } = await req.json();
  if (!pem) return NextResponse.json({ error: "pem required" }, { status: 400 });

  const id = randomBytes(8).toString("hex");
  const pemFile = join(tmpdir(), `${id}.pem`);
  const crtFile = join(tmpdir(), `${id}.crt`);
  const keyFile = join(tmpdir(), `${id}.key`);

  try {
    await writeFile(pemFile, pem);

    // Extract certificate
    let crt = "";
    try {
      const { stdout } = await execAsync(`openssl x509 -in "${pemFile}" -out "${crtFile}"`, { timeout: 10000 });
      crt = await readFile(crtFile, "utf-8");
      void stdout;
    } catch { /* no cert */ }

    // Extract private key
    let key = "";
    try {
      const { stdout } = await execAsync(`openssl pkey -in "${pemFile}" -out "${keyFile}"`, { timeout: 10000 });
      key = await readFile(keyFile, "utf-8");
      void stdout;
    } catch { /* no key */ }

    if (!crt && !key) {
      return NextResponse.json({ error: "No certificate or private key found in PEM input" }, { status: 200 });
    }

    return NextResponse.json({ crt: crt || null, key: key || null });
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : "conversion failed";
    return NextResponse.json({ error: msg }, { status: 200 });
  } finally {
    await Promise.allSettled([unlink(pemFile), unlink(crtFile), unlink(keyFile)]);
  }
}
