import { NextRequest, NextResponse } from "next/server";
import { exec } from "child_process";
import { promisify } from "util";
import { writeFile, unlink } 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 { csr } = await req.json();
  if (!csr) return NextResponse.json({ error: "csr required" }, { status: 400 });

  const id = randomBytes(8).toString("hex");
  const csrFile = join(tmpdir(), `${id}.csr`);

  try {
    await writeFile(csrFile, csr);
    const { stdout } = await execAsync(`openssl req -noout -text -in "${csrFile}"`, { timeout: 10000 });

    // Parse key fields
    const subject = stdout.match(/Subject:\s*(.+)/)?.[1]?.trim();
    const publicKeyAlg = stdout.match(/Public Key Algorithm:\s*(.+)/)?.[1]?.trim();
    const keyBits = stdout.match(/(?:Public-Key|RSA Public-Key):\s*\((\d+)/)?.[1];
    const sigAlg = stdout.match(/Signature Algorithm:\s*(.+)/)?.[1]?.trim();

    const sanMatch = stdout.match(/X509v3 Subject Alternative Name:\s*\n\s*(.+)/);
    const sans = sanMatch ? sanMatch[1].split(",").map((s) => s.trim()) : [];

    const { stdout: pem } = await execAsync(`openssl req -noout -pubkey -in "${csrFile}"`, { timeout: 10000 });

    return NextResponse.json({ subject, publicKeyAlg, keyBits, sigAlg, sans, text: stdout, publicKey: pem });
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : "decode failed";
    return NextResponse.json({ error: msg }, { status: 200 });
  } finally {
    await unlink(csrFile).catch(() => {});
  }
}
