/**
 * Registratura Audit API — Read-only access to audit trail.
 *
 * GET — Retrieve audit events by entry ID or company.
 */

import { NextRequest, NextResponse } from "next/server";
import { getAuthSession } from "@/core/auth";
import {
  getAuditHistory,
  getAuditByCompany,
} from "@/modules/registratura/services/audit-service";

// ── Auth ──

interface Actor {
  id: string;
  name: string;
}

async function authenticateRequest(req: NextRequest): Promise<Actor | null> {
  const session = await getAuthSession();
  if (session?.user) {
    const u = session.user as { id?: string; name?: string | null; email?: string | null };
    return {
      id: u.id ?? u.email ?? "unknown",
      name: u.name ?? u.email ?? "unknown",
    };
  }

  const apiKey = process.env.REGISTRY_API_KEY;
  if (apiKey) {
    const auth = req.headers.get("authorization");
    if (auth === `Bearer ${apiKey}`) {
      return { id: "api-key", name: "ERP Integration" };
    }
  }

  return null;
}

// ── GET — Audit history ──

export async function GET(req: NextRequest) {
  const actor = await authenticateRequest(req);
  if (!actor) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const url = new URL(req.url);
  const entryId = url.searchParams.get("entryId");
  const company = url.searchParams.get("company");
  const from = url.searchParams.get("from");
  const to = url.searchParams.get("to");
  const limit = url.searchParams.get("limit");

  try {
    if (entryId) {
      const events = await getAuditHistory(entryId);
      return NextResponse.json({ success: true, events, total: events.length });
    }

    if (company) {
      const events = await getAuditByCompany(company, {
        from: from ?? undefined,
        to: to ?? undefined,
        limit: limit ? parseInt(limit, 10) : undefined,
      });
      return NextResponse.json({ success: true, events, total: events.length });
    }

    return NextResponse.json(
      { error: "Provide entryId or company query parameter" },
      { status: 400 },
    );
  } catch (err) {
    const message = err instanceof Error ? err.message : "Internal error";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
