/**
 * Security Module Types
 *
 * Type definitions for security scanning:
 * - SBOM (Software Bill of Materials)
 * - Vulnerability scanning with 6 integrated tools
 * - Findings management
 * - CVE tracking
 */

// =============================================================================
// SBOM (Software Bill of Materials)
// =============================================================================

export type SBOMFormat = 'CycloneDX' | 'SPDX'

export type ComponentType =
  | 'library'
  | 'framework'
  | 'application'
  | 'container'
  | 'operating-system'
  | 'device'
  | 'file'

export type LicenseType =
  | 'MIT'
  | 'Apache-2.0'
  | 'GPL-2.0'
  | 'GPL-3.0'
  | 'BSD-2-Clause'
  | 'BSD-3-Clause'
  | 'ISC'
  | 'MPL-2.0'
  | 'LGPL-2.1'
  | 'LGPL-3.0'
  | 'AGPL-3.0'
  | 'Proprietary'
  | 'Unknown'

export interface SBOMComponent {
  name: string
  version: string
  type: ComponentType
  purl: string // Package URL
  licenses: LicenseType[]
  supplier?: string
  author?: string
  description?: string
  hashes?: ComponentHash[]
  vulnerabilities: Vulnerability[]
  dependencies?: string[] // PURLs of dependencies
}

export interface ComponentHash {
  algorithm: 'SHA-256' | 'SHA-384' | 'SHA-512' | 'MD5'
  value: string
}

export interface SBOMDependency {
  from: string // PURL
  to: string   // PURL
}

export interface SBOM {
  format: SBOMFormat
  specVersion: string
  serialNumber?: string
  version: number
  metadata: SBOMMetadata
  components: SBOMComponent[]
  dependencies: SBOMDependency[]
  generatedAt: Date
}

export interface SBOMMetadata {
  timestamp: Date
  tools: SBOMTool[]
  component?: SBOMComponent // The component this SBOM describes
  authors?: string[]
}

export interface SBOMTool {
  vendor: string
  name: string
  version: string
}

// =============================================================================
// VULNERABILITIES
// =============================================================================

export type SecurityIssueSeverity = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO'

export type SecurityIssueStatus = 'OPEN' | 'IN_PROGRESS' | 'RESOLVED' | 'ACCEPTED' | 'FALSE_POSITIVE'

export interface Vulnerability {
  id: string
  cve: string
  severity: SecurityIssueSeverity
  title: string
  description: string
  cvss: CVSSScore | null
  cwe?: string
  fixedIn: string | null
  publishedAt?: Date
  references: string[]
}

export interface CVSSScore {
  version: '2.0' | '3.0' | '3.1'
  score: number
  vector: string
  severity: SecurityIssueSeverity
}

// =============================================================================
// SECURITY SCANNING
// =============================================================================

export type SecurityTool =
  | 'gitleaks'   // Secrets detection
  | 'semgrep'    // SAST
  | 'bandit'     // Python security
  | 'trivy'      // Container/filesystem scanning
  | 'grype'      // Vulnerability scanner
  | 'syft'       // SBOM generation

export type ScreeningStatus = 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED'

export interface SecurityScanConfig {
  tools: SecurityTool[]
  targetPath: string
  excludePaths?: string[]
  severityThreshold?: SecurityIssueSeverity
  failOnFindings?: boolean
  generateSBOM?: boolean
}

export interface SecurityScanResult {
  id: string
  status: ScreeningStatus
  startedAt: Date
  completedAt: Date | null
  duration?: number // ms
  totalIssues: number
  critical: number
  high: number
  medium: number
  low: number
  info: number
  issues: SecurityIssue[]
  toolResults: ToolResult[]
  sbom?: SBOM
  error?: string
}

export interface ToolResult {
  tool: SecurityTool
  status: 'SUCCESS' | 'FAILED' | 'SKIPPED'
  issuesFound: number
  executionTimeMs: number
  version: string
  rawOutput?: string
  error?: string
}

export interface SecurityIssue {
  id: string
  tool: SecurityTool
  severity: SecurityIssueSeverity
  title: string
  description: string
  cve: string | null
  cvss: CVSSScore | null
  cwe?: string
  affectedComponent: string
  affectedFile?: string
  affectedLine?: number
  remediation: string
  status: SecurityIssueStatus
  assignee?: string
  dueDate?: Date
  resolvedAt?: Date
  resolvedBy?: string
  notes?: string
}

// =============================================================================
// FINDINGS MANAGEMENT
// =============================================================================

export interface FindingsFilter {
  tools?: SecurityTool[]
  severities?: SecurityIssueSeverity[]
  statuses?: SecurityIssueStatus[]
  cveIds?: string[]
  components?: string[]
  dateFrom?: Date
  dateTo?: Date
}

export interface FindingsSummary {
  totalFindings: number
  bySeverity: Record<SecurityIssueSeverity, number>
  byStatus: Record<SecurityIssueStatus, number>
  byTool: Record<SecurityTool, number>
  averageResolutionDays: number
  oldestUnresolvedDays: number
}

export interface FindingsReport {
  generatedAt: Date
  period: {
    from: Date
    to: Date
  }
  summary: FindingsSummary
  newFindings: SecurityIssue[]
  resolvedFindings: SecurityIssue[]
  trends: FindingsTrend[]
}

export interface FindingsTrend {
  date: Date
  totalOpen: number
  totalResolved: number
  newFindings: number
}

// =============================================================================
// SECURITY BACKLOG
// =============================================================================

export interface BacklogItem {
  id: string
  title: string
  description: string
  severity: SecurityIssueSeverity
  securityIssueId: string
  status: 'OPEN' | 'IN_PROGRESS' | 'DONE'
  priority: number // 1-5
  assignee: string | null
  dueDate: Date | null
  estimatedHours?: number
  createdAt: Date
  updatedAt: Date
  labels: string[]
}

// =============================================================================
// SECRETS DETECTION (Gitleaks)
// =============================================================================

export interface SecretFinding {
  id: string
  ruleId: string
  description: string
  match: string
  secret: string // Masked
  file: string
  startLine: number
  endLine: number
  commit?: string
  author?: string
  date?: Date
  entropy?: number
}

// =============================================================================
// SAST (Semgrep)
// =============================================================================

export interface SASTFinding {
  id: string
  ruleId: string
  message: string
  severity: SecurityIssueSeverity
  file: string
  startLine: number
  endLine: number
  startCol: number
  endCol: number
  codeSnippet: string
  fix?: SASTFix
  metadata: {
    category: string
    technology: string[]
    cwe?: string
    owasp?: string
    confidence: 'HIGH' | 'MEDIUM' | 'LOW'
  }
}

export interface SASTFix {
  fix: string
  regex_replace?: {
    regex: string
    replacement: string
  }
}

// =============================================================================
// CONTAINER SCANNING (Trivy)
// =============================================================================

export interface ContainerScanResult {
  target: string
  type: 'image' | 'filesystem' | 'repository'
  vulnerabilities: ContainerVulnerability[]
  misconfigurations?: ContainerMisconfiguration[]
  secrets?: SecretFinding[]
}

export interface ContainerVulnerability extends Vulnerability {
  pkgName: string
  installedVersion: string
  fixedVersion?: string
  layer?: {
    digest: string
    diffId: string
    createdBy?: string
  }
}

export interface ContainerMisconfiguration {
  id: string
  title: string
  description: string
  severity: SecurityIssueSeverity
  resolution: string
  type: string
  resource: string
  cause: {
    provider: string
    service: string
    startLine: number
    endLine: number
  }
}

// =============================================================================
// CI/CD INTEGRATION
// =============================================================================

export interface CICDIntegrationConfig {
  provider: 'github' | 'gitlab' | 'jenkins' | 'azure_devops' | 'circleci'
  webhookUrl?: string
  apiToken?: string
  scanOnPush: boolean
  scanOnPR: boolean
  failPipelineOnCritical: boolean
  failPipelineOnHigh: boolean
  notifyOnNewFindings: boolean
  notificationChannels: string[]
}

export interface CICDScanTrigger {
  id: string
  provider: string
  repository: string
  branch: string
  commit: string
  triggeredBy: 'push' | 'pull_request' | 'schedule' | 'manual'
  triggeredAt: Date
  scanResultId?: string
  status: 'QUEUED' | 'RUNNING' | 'COMPLETED' | 'FAILED'
}

// =============================================================================
// COMPLIANCE MAPPING
// =============================================================================

export interface SecurityComplianceMapping {
  issueId: string
  regulation: string
  requirement: string
  article: string
  impact: string
  remediation: string
}
