/**
 * What an administrator did, in one shape every app maps to its own `AuditLog`.
 *
 * The apps' trails agree on the columns — actor id, name and role, a dotted action, the entity, a summary under 300
 * characters, a sanitised `changes` — and disagree on scope: AltEd has no tenants, Quickie and PM Tool record
 * platform actions with a null `organizationId`, and nobody recorded an administrator signing in, starting a view,
 * or being granted the role by script. So the event says its scope outright (`platform`, or one tenant), the actor
 * carries their standing at the time, and a "view as" names both people — the administrator stays the actor, so an
 * entry never reads as though the person being viewed did it.
 *
 * The house writes no table. An app passes an `AdminAuditSink` that maps the event to its own row.
 */

export interface AdminAuditActor {
  id: string;
  name: string;
  /** The actor's standing when they acted: `"platform-admin"`, `"ADMIN"`, an org role — the app's own word. */
  standing: string;
}

export type AdminAuditScope = { kind: "platform" } | { kind: "tenant"; tenantId: string };

export interface AdminAuditEvent {
  /** Dotted, e.g. `admin.signed_in`, `user.role_changed`, `admin.view_as_started`. */
  action: string;
  /** Null for a script or the system: the bootstrap script has nobody to name. */
  actor: AdminAuditActor | null;
  /** Set while the actor is viewing as somebody: who. */
  viewingAs?: { id: string; name: string } | null;
  scope: AdminAuditScope;
  entity: { type: string; id: string | null };
  /** At most 300 characters — the apps' column. The builders trim it. */
  summary: string;
  changes?: Record<string, unknown>;
  at: Date;
  ip?: string | null;
  userAgent?: string | null;
}

export type AdminAuditSink = (event: AdminAuditEvent) => void | Promise<void>;

export const PLATFORM_SCOPE: AdminAuditScope = { kind: "platform" };

export const SUMMARY_MAX = 300;

/** Where the request came from: the first `x-forwarded-for` hop, and the user agent. */
export interface RequestMeta {
  ip?: string | null;
  userAgent?: string | null;
}

/** `{ ip, userAgent }` from a `Request` or its `Headers`. */
export function requestMeta(source: Request | Headers | null | undefined): RequestMeta {
  const headers = source instanceof Headers ? source : source?.headers;
  if (!headers) return {};
  const forwarded = headers.get("x-forwarded-for")?.split(",")[0]?.trim();
  const ip = forwarded || headers.get("x-real-ip") || null;
  return { ip, userAgent: headers.get("user-agent") };
}

const trim = (summary: string) => (summary.length > SUMMARY_MAX ? `${summary.slice(0, SUMMARY_MAX - 1)}…` : summary);

interface Common extends RequestMeta {
  at?: Date;
}

function event(base: Omit<AdminAuditEvent, "at" | "summary"> & { summary: string } & Common): AdminAuditEvent {
  const { at, ip, userAgent, ...rest } = base;
  return {
    ...rest,
    summary: trim(rest.summary),
    at: at ?? new Date(),
    ...(ip !== undefined ? { ip } : {}),
    ...(userAgent !== undefined ? { userAgent } : {}),
  };
}

/**
 * How a sign-in was made. The first four prove the second factor; the rest do not, and an administrator signed in
 * that way is refused administration until they sign in again.
 */
export type AdminSignInMethod =
  "code" | "backup-code" | "passkey" | "trusted-device" | "password" | "email-link" | "social" | "other";

const METHOD_WORDS: Record<AdminSignInMethod, string> = {
  code: "their authenticator code",
  "backup-code": "a backup code",
  passkey: "a passkey",
  "trusted-device": "a password on a trusted device",
  password: "a password, without a second factor",
  "email-link": "an email link, without a second factor",
  social: "a social sign-in, without a second factor",
  other: "a sign-in that did not use a second factor",
};

export function adminSignedIn(
  input: {
    actor: AdminAuditActor;
    sessionId: string;
    method: AdminSignInMethod;
    /** Whether the session counts for administration — its sign-in used the second factor. */
    proven: boolean;
    scope?: AdminAuditScope;
  } & Common,
): AdminAuditEvent {
  return event({
    action: "admin.signed_in",
    actor: input.actor,
    scope: input.scope ?? PLATFORM_SCOPE,
    entity: { type: "session", id: input.sessionId },
    summary: `${input.actor.name} signed in with ${METHOD_WORDS[input.method]}`,
    changes: { method: input.method, proven: input.proven },
    at: input.at,
    ip: input.ip,
    userAgent: input.userAgent,
  });
}

export function roleChanged(
  input: {
    /** Null for a script. */
    actor: AdminAuditActor | null;
    target: { id: string; name?: string | null; email?: string | null };
    /** The standing before and after: `"user"` → `"platform-admin"`, `"MEMBER"` → `"ADMIN"`. Null for none. */
    from: string | null;
    to: string | null;
    scope?: AdminAuditScope;
    /** What made the change when it was not a screen: `"bootstrap-admin"`. */
    via?: string;
    changes?: Record<string, unknown>;
  } & Common,
): AdminAuditEvent {
  const who = input.target.name || input.target.email || input.target.id;
  const by = input.via ? ` (${input.via})` : "";
  const summary =
    input.to === null
      ? `Removed ${who}'s ${input.from ?? "role"} standing${by}`
      : `Changed ${who} from ${input.from ?? "no role"} to ${input.to}${by}`;
  return event({
    action: "user.role_changed",
    actor: input.actor,
    scope: input.scope ?? PLATFORM_SCOPE,
    entity: { type: "user", id: input.target.id },
    summary,
    changes: { from: input.from, to: input.to, ...(input.via ? { via: input.via } : {}), ...input.changes },
    at: input.at,
    ip: input.ip,
    userAgent: input.userAgent,
  });
}

export function viewAsStarted(
  input: {
    actor: AdminAuditActor;
    target: { id: string; name: string };
    expiresAt: Date;
    scope?: AdminAuditScope;
  } & Common,
): AdminAuditEvent {
  return event({
    action: "admin.view_as_started",
    actor: input.actor,
    viewingAs: input.target,
    scope: input.scope ?? PLATFORM_SCOPE,
    entity: { type: "user", id: input.target.id },
    summary: `${input.actor.name} started viewing as ${input.target.name}`,
    changes: { until: input.expiresAt.toISOString() },
    at: input.at,
    ip: input.ip,
    userAgent: input.userAgent,
  });
}

export function viewAsStopped(
  input: {
    actor: AdminAuditActor;
    target: { id: string; name: string };
    scope?: AdminAuditScope;
  } & Common,
): AdminAuditEvent {
  return event({
    action: "admin.view_as_stopped",
    actor: input.actor,
    viewingAs: input.target,
    scope: input.scope ?? PLATFORM_SCOPE,
    entity: { type: "user", id: input.target.id },
    summary: `${input.actor.name} stopped viewing as ${input.target.name}`,
    at: input.at,
    ip: input.ip,
    userAgent: input.userAgent,
  });
}

/** An operator's action across the platform — comps, AI rates, re-pricing — with no tenant of its own. */
export function platformAction(
  input: {
    actor: AdminAuditActor;
    action: string;
    entity: { type: string; id?: string | null };
    summary: string;
    changes?: Record<string, unknown>;
    viewingAs?: { id: string; name: string } | null;
  } & Common,
): AdminAuditEvent {
  return event({
    action: input.action,
    actor: input.actor,
    ...(input.viewingAs ? { viewingAs: input.viewingAs } : {}),
    scope: PLATFORM_SCOPE,
    entity: { type: input.entity.type, id: input.entity.id ?? null },
    summary: input.summary,
    ...(input.changes ? { changes: input.changes } : {}),
    at: input.at,
    ip: input.ip,
    userAgent: input.userAgent,
  });
}

export interface AuditLogger {
  error(message: string, ...args: unknown[]): void;
}

/**
 * Recording an event must never break the thing being recorded: an error from the sink is logged and swallowed.
 * Used wherever the house emits an event beside an action that already happened (a sign-in, a view starting).
 */
export async function emitSafely(
  sink: AdminAuditSink | undefined,
  auditEvent: AdminAuditEvent,
  logger: AuditLogger = console,
): Promise<void> {
  if (!sink) return;
  try {
    await sink(auditEvent);
  } catch (error) {
    logger.error(`[admin] could not record ${auditEvent.action}`, error);
  }
}
