import { prisma } from './prisma';
import { Prisma } from '@prisma/client';

interface AuditOptions {
  userId?: string | null;
  action: string;
  entity: string;
  entityId: string;
  details?: Record<string, unknown>;
  ipAddress?: string | null;
  userAgent?: string | null;
}

/**
 * Registra un evento crítico en el log de auditoría.
 * Nunca lanza excepciones para no interrumpir el flujo principal.
 */
export async function auditLog(options: AuditOptions): Promise<void> {
  try {
    await prisma.auditLog.create({
      data: {
        userId: options.userId || null,
        action: options.action,
        entity: options.entity,
        entityId: options.entityId,
        details: options.details ? (options.details as Prisma.InputJsonValue) : Prisma.JsonNull,
        ipAddress: options.ipAddress || null,
        userAgent: options.userAgent || null,
      },
    });
  } catch (err) {
    // Fallo silencioso: auditoría no debe romper operaciones de negocio
    console.error('[AUDIT_LOG_ERROR]', err);
  }
}

// ─── ACCIONES PREDEFINIDAS ────────────────────────────────────────────────────
export const AUDIT_ACTIONS = {
  // Auth
  LOGIN_SUCCESS: 'LOGIN_SUCCESS',
  LOGIN_FAILED: 'LOGIN_FAILED',
  LOGOUT: 'LOGOUT',
  // Inventario
  INVENTORY_ADJUST: 'INVENTORY_ADJUST',
  STOCK_DISPENSE: 'STOCK_DISPENSE',
  // Órdenes
  ORDER_CREATED: 'ORDER_CREATED',
  ORDER_CANCELLED: 'ORDER_CANCELLED',
  ORDER_ITEM_CANCELLED: 'ORDER_ITEM_CANCELLED',
  // Dispensación
  ITEM_DISPENSED: 'ITEM_DISPENSED',
  ITEM_DELIVERED: 'ITEM_DELIVERED',
  // Facturación
  INVOICE_CREATED: 'INVOICE_CREATED',
  INVOICE_PAID: 'INVOICE_PAID',
  INVOICE_ANNULLED: 'INVOICE_ANNULLED',
  // Caja
  SHIFT_OPENED: 'SHIFT_OPENED',
  SHIFT_CLOSED: 'SHIFT_CLOSED',
  // Usuarios
  USER_CREATED: 'USER_CREATED',
  USER_UPDATED: 'USER_UPDATED',
  USER_DEACTIVATED: 'USER_DEACTIVATED',
  USER_PASSWORD_RESET: 'USER_PASSWORD_RESET',
} as const;
