/**
 * app/api/admin/audit-export/route.js
 *
 * GET /api/admin/audit-export?format=ndjson|csv&since=ISO&until=ISO
 *
 * Owner-only. Streams all audit_logs rows for the caller's org in the date
 * range as NDJSON (one JSON object per line) or CSV.
 *
 * Security: values are emitted as-is from audit_logs — no artifact content,
 * no decryption. This endpoint only surfaces audit metadata rows.
 */

import { getDb } from '@/lib/db.js';
import { requireSession } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const CSV_COLUMNS = ['id', 'at', 'type', 'summary', 'status', 'user_id', 'org_id', 'project_id', 'ip', 'action_target_id', 'action_target_type', 'correlation_id'];

function csvEscape(value) {
  if (value === null || value === undefined) return '';
  const str = String(value);
  // Wrap in double-quotes if contains comma, newline, or double-quote.
  if (str.includes('"') || str.includes(',') || str.includes('\n') || str.includes('\r')) {
    return `"${str.replace(/"/g, '""')}"`;
  }
  return str;
}

function rowToCsv(row) {
  return CSV_COLUMNS.map(col => csvEscape(row[col])).join(',');
}

export async function GET(req) {
  let session;
  try {
    session = await requireSession(req);
    requireRole(session, 'owner');
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    console.error('GET /api/admin/audit-export auth error:', err);
    throw err;
  }

  const { searchParams } = new URL(req.url);
  const format = searchParams.get('format') || 'ndjson';
  const since = searchParams.get('since') || null;
  const until = searchParams.get('until') || null;

  if (format !== 'ndjson' && format !== 'csv') {
    return Response.json({ error: 'format must be ndjson or csv' }, { status: 400 });
  }

  const db = getDb();
  const orgId = session.org_id;

  // Build parameterized query — only audit_logs rows for this org.
  const conditions = ['org_id = ?'];
  const binds = [orgId];
  if (since) { conditions.push('at >= ?'); binds.push(since); }
  if (until) { conditions.push('at <= ?'); binds.push(until); }

  const rows = db.prepare(
    `SELECT ${CSV_COLUMNS.join(', ')} FROM audit_logs
     WHERE ${conditions.join(' AND ')}
     ORDER BY at ASC`
  ).all(...binds);

  const date = new Date().toISOString().slice(0, 10);

  if (format === 'csv') {
    const header = CSV_COLUMNS.join(',');
    const body = [header, ...rows.map(rowToCsv)].join('\n');
    return new Response(body, {
      status: 200,
      headers: {
        'Content-Type': 'text/csv; charset=utf-8',
        'Content-Disposition': `attachment; filename="madarx-audit-${date}.csv"`,
      },
    });
  }

  // NDJSON: one JSON object per line.
  const body = rows.map(row => JSON.stringify(row)).join('\n');
  return new Response(body, {
    status: 200,
    headers: {
      'Content-Type': 'application/x-ndjson',
      'Content-Disposition': `attachment; filename="madarx-audit-${date}.ndjson"`,
    },
  });
}
