import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';
import fs from 'fs';
import path from 'path';

export const dynamic = 'force-dynamic';

const CA_CERT_PATH = '/etc/xcu-sovereign-ca/ca.crt';

// GET: Download the Sovereign CA certificate
export async function GET() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('jumpa_token')?.value;
    if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as { role: string };
    if (decoded.role !== 'superadmin' && decoded.role !== 'admin') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    if (!fs.existsSync(CA_CERT_PATH)) {
      return NextResponse.json({ error: 'CA Certificate not generated yet. Contact Supreme Admin.' }, { status: 404 });
    }

    const certData = fs.readFileSync(CA_CERT_PATH);
    return new NextResponse(certData, {
      headers: {
        'Content-Type': 'application/x-x509-ca-cert',
        'Content-Disposition': 'attachment; filename="xcu-sovereign-ca.crt"',
        'Cache-Control': 'no-store',
      },
    });
  } catch (_e) {
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}
