// =============================================================================
// Loeschfristen Module - TypeScript Types
// 3-Level Loeschlogik: Zweckende -> Aufbewahrungstreiber -> Legal Hold
// =============================================================================

// =============================================================================
// ENUMS & LITERAL TYPES
// =============================================================================

export type DeletionTriggerLevel = 'PURPOSE_END' | 'RETENTION_DRIVER' | 'LEGAL_HOLD'

export type RetentionDriverType =
  | 'AO_147'      // 10 Jahre Steuerunterlagen
  | 'HGB_257'     // 10/6 Jahre Handelsbuecher/-briefe
  | 'USTG_14B'    // 10 Jahre Rechnungen
  | 'BGB_195'     // 3 Jahre Verjaehrung
  | 'ARBZG_16'    // 2 Jahre Zeiterfassung
  | 'AGG_15'      // 6 Monate Bewerbungen
  | 'BDSG_35'     // Unverzuegliche Loeschung
  | 'BSIG'        // 90 Tage Sicherheitslogs
  | 'CUSTOM'

export type DeletionMethodType =
  | 'AUTO_DELETE'
  | 'MANUAL_REVIEW_DELETE'
  | 'ANONYMIZATION'
  | 'AGGREGATION'
  | 'CRYPTO_ERASE'
  | 'PHYSICAL_DESTROY'

export type PolicyStatus = 'DRAFT' | 'ACTIVE' | 'REVIEW_NEEDED' | 'ARCHIVED'

export type ReviewInterval = 'QUARTERLY' | 'SEMI_ANNUAL' | 'ANNUAL'

export type RetentionUnit = 'DAYS' | 'MONTHS' | 'YEARS'

export type StorageLocationType =
  | 'DATABASE' | 'FILE_SYSTEM' | 'CLOUD' | 'EMAIL' | 'BACKUP' | 'PAPER' | 'OTHER'

export type LegalHoldStatus = 'ACTIVE' | 'RELEASED' | 'EXPIRED'

// =============================================================================
// INTERFACES
// =============================================================================

export interface LegalHold {
  id: string
  reason: string
  legalBasis: string
  responsiblePerson: string
  startDate: string
  expectedEndDate: string | null
  actualEndDate: string | null
  status: LegalHoldStatus
  affectedDataCategories: string[]
}

export interface StorageLocation {
  id: string
  name: string
  type: StorageLocationType
  isBackup: boolean
  provider: string | null
  deletionCapable: boolean
}

export interface LoeschfristPolicy {
  id: string
  policyId: string // LF-2026-001
  dataObjectName: string
  description: string
  affectedGroups: string[]
  dataCategories: string[]
  primaryPurpose: string
  // 3-Level Loeschlogik
  deletionTrigger: DeletionTriggerLevel
  retentionDriver: RetentionDriverType | null
  retentionDriverDetail: string
  retentionDuration: number | null
  retentionUnit: RetentionUnit | null
  retentionDescription: string
  startEvent: string
  hasActiveLegalHold: boolean
  legalHolds: LegalHold[]
  // Speicherorte & Loeschung
  storageLocations: StorageLocation[]
  deletionMethod: DeletionMethodType
  deletionMethodDetail: string
  // Verantwortung & Workflow
  responsibleRole: string
  responsiblePerson: string
  releaseProcess: string
  linkedVVTActivityIds: string[]
  // Status & Review
  status: PolicyStatus
  lastReviewDate: string
  nextReviewDate: string
  reviewInterval: ReviewInterval
  tags: string[]
  createdAt: string
  updatedAt: string
}

// =============================================================================
// CONSTANTS
// =============================================================================

export interface RetentionDriverMeta {
  label: string
  statute: string
  defaultDuration: number | null
  defaultUnit: RetentionUnit | null
  description: string
}

export const RETENTION_DRIVER_META: Record<RetentionDriverType, RetentionDriverMeta> = {
  AO_147: {
    label: 'Abgabenordnung (AO) 147',
    statute: '147 AO',
    defaultDuration: 10,
    defaultUnit: 'YEARS',
    description: 'Aufbewahrung steuerrelevanter Unterlagen (Buchungsbelege, Bilanzen, Jahresabschluesse)',
  },
  HGB_257: {
    label: 'Handelsgesetzbuch (HGB) 257',
    statute: '257 HGB',
    defaultDuration: 10,
    defaultUnit: 'YEARS',
    description: 'Handelsbuecher und Buchungsbelege (10 J.), empfangene/gesendete Handelsbriefe (6 J.)',
  },
  USTG_14B: {
    label: 'Umsatzsteuergesetz (UStG) 14b',
    statute: '14b UStG',
    defaultDuration: 10,
    defaultUnit: 'YEARS',
    description: 'Aufbewahrung von Rechnungen und rechnungsbegruendenden Unterlagen',
  },
  BGB_195: {
    label: 'Buergerliches Gesetzbuch (BGB) 195',
    statute: '195 BGB',
    defaultDuration: 3,
    defaultUnit: 'YEARS',
    description: 'Regelmaessige Verjaehrungsfrist fuer vertragliche Ansprueche',
  },
  ARBZG_16: {
    label: 'Arbeitszeitgesetz (ArbZG) 16',
    statute: '16 Abs. 2 ArbZG',
    defaultDuration: 2,
    defaultUnit: 'YEARS',
    description: 'Aufbewahrung von Arbeitszeitaufzeichnungen',
  },
  AGG_15: {
    label: 'Allg. Gleichbehandlungsgesetz (AGG) 15',
    statute: '15 Abs. 4 AGG',
    defaultDuration: 6,
    defaultUnit: 'MONTHS',
    description: 'Frist fuer Geltendmachung von Entschaedigungsanspruechen nach Absage',
  },
  BDSG_35: {
    label: 'BDSG 35 / DSGVO Art. 17',
    statute: '35 BDSG / Art. 17 DSGVO',
    defaultDuration: null,
    defaultUnit: null,
    description: 'Unverzuegliche Loeschung nach Zweckwegfall (kein fester Zeitraum)',
  },
  BSIG: {
    label: 'BSI-Gesetz (BSIG)',
    statute: 'BSIG / IT-SiG 2.0',
    defaultDuration: 90,
    defaultUnit: 'DAYS',
    description: 'Aufbewahrung von Sicherheitslogs fuer Vorfallsanalyse',
  },
  CUSTOM: {
    label: 'Individuelle Frist',
    statute: 'Individuell',
    defaultDuration: null,
    defaultUnit: null,
    description: 'Benutzerdefinierte Aufbewahrungsfrist',
  },
}

export const DELETION_METHOD_LABELS: Record<DeletionMethodType, string> = {
  AUTO_DELETE: 'Automatische Loeschung',
  MANUAL_REVIEW_DELETE: 'Manuelle Pruefung & Loeschung',
  ANONYMIZATION: 'Anonymisierung',
  AGGREGATION: 'Aggregation (statistische Verdichtung)',
  CRYPTO_ERASE: 'Kryptographische Loeschung',
  PHYSICAL_DESTROY: 'Physische Vernichtung',
}

export const STATUS_LABELS: Record<PolicyStatus, string> = {
  DRAFT: 'Entwurf',
  ACTIVE: 'Aktiv',
  REVIEW_NEEDED: 'Pruefung erforderlich',
  ARCHIVED: 'Archiviert',
}

export const STATUS_COLORS: Record<PolicyStatus, string> = {
  DRAFT: 'bg-gray-100 text-gray-700 border-gray-200',
  ACTIVE: 'bg-green-100 text-green-700 border-green-200',
  REVIEW_NEEDED: 'bg-yellow-100 text-yellow-700 border-yellow-200',
  ARCHIVED: 'bg-blue-100 text-blue-700 border-blue-200',
}

export const TRIGGER_LABELS: Record<DeletionTriggerLevel, string> = {
  PURPOSE_END: 'Zweckende',
  RETENTION_DRIVER: 'Aufbewahrungspflicht',
  LEGAL_HOLD: 'Legal Hold',
}

export const TRIGGER_COLORS: Record<DeletionTriggerLevel, string> = {
  PURPOSE_END: 'bg-green-100 text-green-700',
  RETENTION_DRIVER: 'bg-blue-100 text-blue-700',
  LEGAL_HOLD: 'bg-red-100 text-red-700',
}

export const REVIEW_INTERVAL_LABELS: Record<ReviewInterval, string> = {
  QUARTERLY: 'Vierteljaehrlich',
  SEMI_ANNUAL: 'Halbjaehrlich',
  ANNUAL: 'Jaehrlich',
}

export const STORAGE_LOCATION_LABELS: Record<StorageLocationType, string> = {
  DATABASE: 'Datenbank',
  FILE_SYSTEM: 'Dateisystem',
  CLOUD: 'Cloud-Speicher',
  EMAIL: 'E-Mail-System',
  BACKUP: 'Backup-System',
  PAPER: 'Papierarchiv',
  OTHER: 'Sonstiges',
}

// =============================================================================
// HELPER FUNCTIONS
// =============================================================================

let policyCounter = 0

export function generatePolicyId(): string {
  policyCounter++
  const year = new Date().getFullYear()
  const num = String(policyCounter).padStart(3, '0')
  return `LF-${year}-${num}`
}

export function createEmptyPolicy(): LoeschfristPolicy {
  const now = new Date().toISOString()
  const nextYear = new Date()
  nextYear.setFullYear(nextYear.getFullYear() + 1)

  return {
    id: crypto.randomUUID(),
    policyId: generatePolicyId(),
    dataObjectName: '',
    description: '',
    affectedGroups: [],
    dataCategories: [],
    primaryPurpose: '',
    deletionTrigger: 'PURPOSE_END',
    retentionDriver: null,
    retentionDriverDetail: '',
    retentionDuration: null,
    retentionUnit: null,
    retentionDescription: '',
    startEvent: '',
    hasActiveLegalHold: false,
    legalHolds: [],
    storageLocations: [],
    deletionMethod: 'AUTO_DELETE',
    deletionMethodDetail: '',
    responsibleRole: '',
    responsiblePerson: '',
    releaseProcess: '',
    linkedVVTActivityIds: [],
    status: 'DRAFT',
    lastReviewDate: now,
    nextReviewDate: nextYear.toISOString(),
    reviewInterval: 'ANNUAL',
    tags: [],
    createdAt: now,
    updatedAt: now,
  }
}

export function createEmptyLegalHold(): LegalHold {
  return {
    id: crypto.randomUUID(),
    reason: '',
    legalBasis: '',
    responsiblePerson: '',
    startDate: new Date().toISOString().split('T')[0],
    expectedEndDate: null,
    actualEndDate: null,
    status: 'ACTIVE',
    affectedDataCategories: [],
  }
}

export function createEmptyStorageLocation(): StorageLocation {
  return {
    id: crypto.randomUUID(),
    name: '',
    type: 'DATABASE',
    isBackup: false,
    provider: null,
    deletionCapable: true,
  }
}

export function formatRetentionDuration(
  duration: number | null,
  unit: RetentionUnit | null
): string {
  if (duration === null || unit === null) return 'Bis Zweckwegfall'
  const unitLabels: Record<RetentionUnit, string> = {
    DAYS: duration === 1 ? 'Tag' : 'Tage',
    MONTHS: duration === 1 ? 'Monat' : 'Monate',
    YEARS: duration === 1 ? 'Jahr' : 'Jahre',
  }
  return `${duration} ${unitLabels[unit]}`
}

export function isPolicyOverdue(policy: LoeschfristPolicy): boolean {
  if (!policy.nextReviewDate) return false
  return new Date(policy.nextReviewDate) <= new Date()
}

export function getActiveLegalHolds(policy: LoeschfristPolicy): LegalHold[] {
  return policy.legalHolds.filter(h => h.status === 'ACTIVE')
}

export function getEffectiveDeletionTrigger(policy: LoeschfristPolicy): DeletionTriggerLevel {
  if (policy.hasActiveLegalHold && getActiveLegalHolds(policy).length > 0) {
    return 'LEGAL_HOLD'
  }
  if (policy.retentionDriver && policy.retentionDriver !== 'CUSTOM') {
    return 'RETENTION_DRIVER'
  }
  return 'PURPOSE_END'
}

// =============================================================================
// LOCALSTORAGE KEY
// =============================================================================

export const LOESCHFRISTEN_STORAGE_KEY = 'bp_loeschfristen'
