import "server-only";
import { headers } from "next/headers";
import { prisma } from "@/lib/db";
import type { Prisma } from "@prisma/client";

/**
 * Audit trail.
 *
 * Every security-relevant or state-changing operation records an entry so the
 * admin console can answer "who did what, when". Writes are best-effort: an
 * audit failure must never roll back the user's actual action.
 */
export interface AuditInput {
  actorId?: string | null;
  action: string;
  entity?: string;
  entityId?: string;
  metadata?: Prisma.InputJsonValue;
}

export async function recordAudit(input: AuditInput): Promise<void> {
  let ipAddress: string | null = null;
  try {
    const headerList = await headers();
    ipAddress =
      headerList.get("x-forwarded-for")?.split(",")[0]?.trim() ??
      headerList.get("x-real-ip") ??
      null;
  } catch {
    // Outside a request scope (seed scripts, background jobs).
  }

  await prisma.auditLog
    .create({
      data: {
        actorId: input.actorId ?? null,
        action: input.action,
        entity: input.entity ?? null,
        entityId: input.entityId ?? null,
        metadata: input.metadata ?? undefined,
        ipAddress,
      },
    })
    .catch(() => {});
}

/**
 * Count recent failed sign-in attempts for a username, used to throttle
 * credential stuffing without locking out a legitimate user permanently.
 */
export async function recentFailedLogins(username: string, windowMinutes: number): Promise<number> {
  const since = new Date(Date.now() - windowMinutes * 60 * 1000);
  return prisma.auditLog.count({
    where: {
      action: "LOGIN_FAILED",
      entity: "User",
      entityId: username.toLowerCase(),
      createdAt: { gte: since },
    },
  });
}

export async function recordFailedLogin(username: string, reason: string): Promise<void> {
  await recordAudit({
    action: "LOGIN_FAILED",
    entity: "User",
    entityId: username.toLowerCase(),
    metadata: { reason },
  });
}
