import { logAdminAction } from "../db.admin.ts";

export interface AdminAuditEvent {
  adminId: number;
  actionType: string;
  entityType: string;
  entityId: string;
  oldValues?: Record<string, any>;
  newValues?: Record<string, any>;
  reason?: string;
  ipAddress?: string;
  userAgent?: string;
}

/**
 * Admin Audit Logging System
 * Tracks all admin actions for compliance and security
 */

export class AdminAuditLogger {
  /**
   * Log a game update action
   */
  static async logGameUpdate(
    adminId: number,
    gameId: string,
    oldValues: Record<string, any>,
    newValues: Record<string, any>,
    reason?: string,
    ipAddress?: string
  ) {
    return logAdminAction(
      adminId,
      'GAME_UPDATE',
      'GAME',
      gameId,
      oldValues,
      newValues,
      reason,
      ipAddress
    );
  }

  /**
   * Log a player action (suspend, ban, bonus, etc.)
   */
  static async logPlayerAction(
    adminId: number,
    playerId: string,
    actionType: 'SUSPEND' | 'BAN' | 'UNSUSPEND' | 'BONUS' | 'RESET' | 'VERIFY',
    oldValues: Record<string, any>,
    newValues: Record<string, any>,
    reason?: string,
    ipAddress?: string
  ) {
    return logAdminAction(
      adminId,
      `PLAYER_${actionType}`,
      'PLAYER',
      playerId,
      oldValues,
      newValues,
      reason,
      ipAddress
    );
  }

  /**
   * Log a support ticket action
   */
  static async logTicketAction(
    adminId: number,
    ticketId: string,
    actionType: 'ASSIGN' | 'UPDATE_STATUS' | 'REPLY' | 'CLOSE' | 'REOPEN',
    oldValues: Record<string, any>,
    newValues: Record<string, any>,
    reason?: string,
    ipAddress?: string
  ) {
    return logAdminAction(
      adminId,
      `TICKET_${actionType}`,
      'TICKET',
      ticketId,
      oldValues,
      newValues,
      reason,
      ipAddress
    );
  }

  /**
   * Log a fraud alert action
   */
  static async logFraudAction(
    adminId: number,
    alertId: string,
    actionType: 'REVIEW' | 'RESOLVE' | 'ESCALATE' | 'DISMISS',
    oldValues: Record<string, any>,
    newValues: Record<string, any>,
    reason?: string,
    ipAddress?: string
  ) {
    return logAdminAction(
      adminId,
      `FRAUD_${actionType}`,
      'FRAUD_ALERT',
      alertId,
      oldValues,
      newValues,
      reason,
      ipAddress
    );
  }

  /**
   * Log a system configuration change
   */
  static async logConfigChange(
    adminId: number,
    configKey: string,
    oldValue: any,
    newValue: any,
    reason?: string,
    ipAddress?: string
  ) {
    return logAdminAction(
      adminId,
      'CONFIG_UPDATE',
      'SYSTEM_CONFIG',
      configKey,
      { value: oldValue },
      { value: newValue },
      reason,
      ipAddress
    );
  }

  /**
   * Log a player segment action
   */
  static async logSegmentAction(
    adminId: number,
    segmentId: string,
    actionType: 'CREATE' | 'UPDATE' | 'DELETE' | 'ADD_MEMBER' | 'REMOVE_MEMBER',
    oldValues: Record<string, any>,
    newValues: Record<string, any>,
    reason?: string,
    ipAddress?: string
  ) {
    return logAdminAction(
      adminId,
      `SEGMENT_${actionType}`,
      'PLAYER_SEGMENT',
      segmentId,
      oldValues,
      newValues,
      reason,
      ipAddress
    );
  }

  /**
   * Log a bulk action
   */
  static async logBulkAction(
    adminId: number,
    actionType: string,
    entityType: string,
    affectedCount: number,
    criteria: Record<string, any>,
    reason?: string,
    ipAddress?: string
  ) {
    return logAdminAction(
      adminId,
      `BULK_${actionType}`,
      entityType,
      `bulk_${Date.now()}`,
      { criteria, affectedCount },
      { affectedCount },
      reason,
      ipAddress
    );
  }

  /**
   * Log a login attempt
   */
  static async logLoginAttempt(
    adminId: number,
    success: boolean,
    ipAddress?: string,
    userAgent?: string
  ) {
    return logAdminAction(
      adminId,
      success ? 'LOGIN_SUCCESS' : 'LOGIN_FAILED',
      'ADMIN',
      adminId.toString(),
      { attempt: 'login' },
      { success, timestamp: new Date() },
      undefined,
      ipAddress
    );
  }

  /**
   * Log a permission change
   */
  static async logPermissionChange(
    adminId: number,
    targetAdminId: number,
    oldRole: string,
    newRole: string,
    reason?: string,
    ipAddress?: string
  ) {
    return logAdminAction(
      adminId,
      'PERMISSION_UPDATE',
      'ADMIN',
      targetAdminId.toString(),
      { role: oldRole },
      { role: newRole },
      reason,
      ipAddress
    );
  }

  /**
   * Log a data export
   */
  static async logDataExport(
    adminId: number,
    exportType: string,
    recordCount: number,
    filters: Record<string, any>,
    ipAddress?: string
  ) {
    return logAdminAction(
      adminId,
      'DATA_EXPORT',
      'EXPORT',
      `export_${Date.now()}`,
      { type: exportType, recordCount },
      { type: exportType, recordCount, timestamp: new Date() },
      undefined,
      ipAddress
    );
  }
}

/**
 * Helper function to extract IP address from request
 */
export function getClientIp(req: any): string {
  return (
    req.headers['x-forwarded-for']?.split(',')[0].trim() ||
    req.headers['x-real-ip'] ||
    req.socket?.remoteAddress ||
    'unknown'
  );
}

/**
 * Helper function to extract user agent from request
 */
export function getUserAgent(req: any): string {
  return req.headers['user-agent'] || 'unknown';
}
