/**
 * سرویس حسابرسی (Audit).
 * فقط افزودنی است: هیچ متدی برای حذف یا ویرایش رکوردهای حسابرسی وجود ندارد.
 */
import { getDb } from '../../database/client.js';
import { auditLogs } from '../../database/schema/index.js';

export type AuditInput = {
  action: string;
  actorId?: string | null;
  actorLabel?: string | null;
  entityType?: string | null;
  entityId?: string | null;
  ip?: string | null;
  userAgent?: string | null;
  before?: Record<string, unknown> | null;
  after?: Record<string, unknown> | null;
  metadata?: Record<string, unknown>;
};

export async function recordAudit(input: AuditInput): Promise<void> {
  await getDb().insert(auditLogs).values({
    action: input.action,
    actorId: input.actorId ?? null,
    actorLabel: input.actorLabel ?? null,
    entityType: input.entityType ?? null,
    entityId: input.entityId ?? null,
    ip: input.ip ?? null,
    userAgent: input.userAgent ?? null,
    before: input.before ?? null,
    after: input.after ?? null,
    metadata: input.metadata ?? {},
  });
}

export const AuditActions = {
  LOGIN: 'auth.login',
  LOGIN_FAILED: 'auth.login_failed',
  LOGOUT: 'auth.logout',
  ROLE_CHANGE: 'rbac.role_change',
  PERMISSION_CHANGE: 'rbac.permission_change',
  ARTICLE_PUBLISH: 'article.publish',
  ARTICLE_EDIT: 'article.edit',
  ARTICLE_EDIT_DENIED: 'article.edit_denied_locked',
  ARTICLE_CORRECTION: 'article.correction',
  ARTICLE_DELETE_DENIED: 'article.delete_denied',
  REPORT_SUBMIT: 'report.submit',
  REPORT_MODERATE: 'report.moderate',
  REPORT_ROUTE: 'report.route',
  CASE_ASSIGN: 'case.assign',
  CASE_STATUS: 'case.status_change',
  CASE_SLA_BREACH: 'case.sla_breach',
  CASE_ESCALATION: 'case.escalation',
  ORG_RESPONSE: 'organization.response',
  BUSINESS_VERIFY: 'business.verify',
  ORG_VERIFY: 'organization.verify',
  COMMUNICATION_CHANGE: 'communication.change',
  USER_DELETE: 'user.delete',
  SETTINGS_CHANGE: 'settings.change',
  UPLOAD_REJECTED: 'media.upload_rejected',
} as const;
