import type { ComplianceRequirement, DeploymentMilestone, CostEstimate, NetworkTopology } from '../types/infrastructure'

export type AuditAction = 
  | 'create'
  | 'update'
  | 'delete'
  | 'export'
  | 'import'
  | 'backup'
  | 'restore'

export type AuditEntityType =
  | 'compliance'
  | 'milestone'
  | 'cost'
  | 'topology'
  | 'backup'
  | 'import'

export interface AuditLogEntry {
  id: string
  timestamp: string
  userId?: string
  action: AuditAction
  entityType: AuditEntityType
  entityId: string
  entityName: string
  changes?: {
    before?: any
    after?: any
  }
  metadata?: Record<string, any>
}

class AuditLogService {
  private logs: AuditLogEntry[] = []
  private maxLogs = 10000

  log(entry: Omit<AuditLogEntry, 'id' | 'timestamp'>): void {
    const logEntry: AuditLogEntry = {
      ...entry,
      id: `audit-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      timestamp: new Date().toISOString(),
    }

    this.logs.push(logEntry)

    // Keep only the last maxLogs entries
    if (this.logs.length > this.maxLogs) {
      this.logs = this.logs.slice(-this.maxLogs)
    }

    // In production, also persist to database or external service
    this.persistLog(logEntry)
  }

  private async persistLog(entry: AuditLogEntry): Promise<void> {
    try {
      // Save to JSON file (in production, use database)
      if (typeof window === 'undefined') {
        const fs = await import('fs/promises')
        const path = await import('path')
        const logDir = path.join(process.cwd(), 'docs/infrastructure/audit-logs')
        const logFile = path.join(logDir, `audit-${new Date().toISOString().split('T')[0]}.json`)
        
        try {
          await fs.mkdir(logDir, { recursive: true })
          let existingLogs: AuditLogEntry[] = []
          try {
            const content = await fs.readFile(logFile, 'utf-8')
            existingLogs = JSON.parse(content)
          } catch {
            // File doesn't exist yet
          }
          existingLogs.push(entry)
          await fs.writeFile(logFile, JSON.stringify(existingLogs, null, 2))
        } catch (error) {
          console.error('Failed to persist audit log:', error)
        }
      }
    } catch (error) {
      console.error('Failed to persist audit log:', error)
    }
  }

  getLogs(filters?: {
    action?: AuditAction
    entityType?: AuditEntityType
    entityId?: string
    startDate?: string
    endDate?: string
  }): AuditLogEntry[] {
    let filtered = [...this.logs]

    if (filters?.action) {
      filtered = filtered.filter((log) => log.action === filters.action)
    }
    if (filters?.entityType) {
      filtered = filtered.filter((log) => log.entityType === filters.entityType)
    }
    if (filters?.entityId) {
      filtered = filtered.filter((log) => log.entityId === filters.entityId)
    }
    if (filters?.startDate) {
      filtered = filtered.filter((log) => log.timestamp >= filters.startDate!)
    }
    if (filters?.endDate) {
      filtered = filtered.filter((log) => log.timestamp <= filters.endDate!)
    }

    return filtered.sort((a, b) => 
      new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
    )
  }

  getLogsByEntity(entityType: AuditEntityType, entityId: string): AuditLogEntry[] {
    return this.getLogs({ entityType, entityId })
  }

  clear(): void {
    this.logs = []
  }
}

export const auditLogService = new AuditLogService()

