// =============================================================================
// TOM Generator Module - TypeScript Types
// DSGVO Art. 32 Technical and Organizational Measures
// =============================================================================

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

export type TOMGeneratorStepId =
  | 'scope-roles'
  | 'data-categories'
  | 'architecture-hosting'
  | 'security-profile'
  | 'risk-protection'
  | 'review-export'

export type CompanyRole = 'CONTROLLER' | 'PROCESSOR' | 'JOINT_CONTROLLER'

export type DataCategory =
  | 'IDENTIFICATION'
  | 'CONTACT'
  | 'FINANCIAL'
  | 'PROFESSIONAL'
  | 'LOCATION'
  | 'BEHAVIORAL'
  | 'BIOMETRIC'
  | 'HEALTH'
  | 'GENETIC'
  | 'POLITICAL'
  | 'RELIGIOUS'
  | 'SEXUAL_ORIENTATION'
  | 'CRIMINAL'

export type DataSubject =
  | 'EMPLOYEES'
  | 'CUSTOMERS'
  | 'PROSPECTS'
  | 'SUPPLIERS'
  | 'MINORS'
  | 'PATIENTS'
  | 'STUDENTS'
  | 'GENERAL_PUBLIC'

export type HostingLocation =
  | 'DE'
  | 'EU'
  | 'EEA'
  | 'THIRD_COUNTRY_ADEQUATE'
  | 'THIRD_COUNTRY'

export type HostingModel = 'ON_PREMISE' | 'PRIVATE_CLOUD' | 'PUBLIC_CLOUD' | 'HYBRID'

export type MultiTenancy = 'SINGLE_TENANT' | 'MULTI_TENANT' | 'DEDICATED'

export type ControlApplicability =
  | 'REQUIRED'
  | 'RECOMMENDED'
  | 'OPTIONAL'
  | 'NOT_APPLICABLE'

export type DocumentType =
  | 'AVV'
  | 'DPA'
  | 'SLA'
  | 'NDA'
  | 'POLICY'
  | 'CERTIFICATE'
  | 'AUDIT_REPORT'
  | 'OTHER'

export type ProtectionLevel = 'NORMAL' | 'HIGH' | 'VERY_HIGH'

export type CIARating = 1 | 2 | 3 | 4 | 5

export type ControlCategory =
  | 'ACCESS_CONTROL'
  | 'ADMISSION_CONTROL'
  | 'ACCESS_AUTHORIZATION'
  | 'TRANSFER_CONTROL'
  | 'INPUT_CONTROL'
  | 'ORDER_CONTROL'
  | 'AVAILABILITY'
  | 'SEPARATION'
  | 'ENCRYPTION'
  | 'PSEUDONYMIZATION'
  | 'RESILIENCE'
  | 'RECOVERY'
  | 'REVIEW'

export type CompanySize = 'MICRO' | 'SMALL' | 'MEDIUM' | 'LARGE' | 'ENTERPRISE'

export type DataVolume = 'LOW' | 'MEDIUM' | 'HIGH' | 'VERY_HIGH'

export type AuthMethodType =
  | 'PASSWORD'
  | 'MFA'
  | 'SSO'
  | 'CERTIFICATE'
  | 'BIOMETRIC'

export type BackupFrequency = 'HOURLY' | 'DAILY' | 'WEEKLY' | 'MONTHLY'

export type ReviewFrequency = 'MONTHLY' | 'QUARTERLY' | 'SEMI_ANNUAL' | 'ANNUAL'

export type ControlPriority = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'

export type ControlComplexity = 'LOW' | 'MEDIUM' | 'HIGH'

export type ImplementationStatus = 'NOT_IMPLEMENTED' | 'PARTIAL' | 'IMPLEMENTED'

export type EvidenceStatus = 'PENDING' | 'ANALYZED' | 'VERIFIED' | 'REJECTED'

export type ConditionOperator =
  | 'EQUALS'
  | 'NOT_EQUALS'
  | 'CONTAINS'
  | 'GREATER_THAN'
  | 'IN'

// =============================================================================
// PROFILE INTERFACES (Wizard Steps 1-5)
// =============================================================================

export interface CompanyProfile {
  id: string
  name: string
  industry: string
  size: CompanySize
  role: CompanyRole
  products: string[]
  dpoPerson: string | null
  dpoEmail: string | null
  itSecurityContact: string | null
}

export interface DataProfile {
  categories: DataCategory[]
  subjects: DataSubject[]
  hasSpecialCategories: boolean
  processesMinors: boolean
  dataVolume: DataVolume
  thirdCountryTransfers: boolean
  thirdCountryList: string[]
}

export interface CloudProvider {
  name: string
  location: HostingLocation
  certifications: string[]
}

export interface ArchitectureProfile {
  hostingModel: HostingModel
  hostingLocation: HostingLocation
  providers: CloudProvider[]
  multiTenancy: MultiTenancy
  hasSubprocessors: boolean
  subprocessorCount: number
  encryptionAtRest: boolean
  encryptionInTransit: boolean
}

export interface AuthMethod {
  type: AuthMethodType
  provider: string | null
}

export interface SecurityProfile {
  authMethods: AuthMethod[]
  hasMFA: boolean
  hasSSO: boolean
  hasIAM: boolean
  hasPAM: boolean
  hasEncryptionAtRest: boolean
  hasEncryptionInTransit: boolean
  hasLogging: boolean
  logRetentionDays: number
  hasBackup: boolean
  backupFrequency: BackupFrequency
  backupRetentionDays: number
  hasDRPlan: boolean
  rtoHours: number | null
  rpoHours: number | null
  hasVulnerabilityManagement: boolean
  hasPenetrationTests: boolean
  hasSecurityTraining: boolean
}

export interface CIAAssessment {
  confidentiality: CIARating
  integrity: CIARating
  availability: CIARating
  justification: string
}

export interface RiskProfile {
  ciaAssessment: CIAAssessment
  protectionLevel: ProtectionLevel
  specialRisks: string[]
  regulatoryRequirements: string[]
  hasHighRiskProcessing: boolean
  dsfaRequired: boolean
}

// =============================================================================
// EVIDENCE DOCUMENT
// =============================================================================

export interface ExtractedClause {
  id: string
  text: string
  type: string
  relatedControlId: string | null
}

export interface AIDocumentAnalysis {
  summary: string
  extractedClauses: ExtractedClause[]
  applicableControls: string[]
  gaps: string[]
  confidence: number
  analyzedAt: Date
}

export interface EvidenceDocument {
  id: string
  filename: string
  originalName: string
  mimeType: string
  size: number
  uploadedAt: Date
  uploadedBy: string
  documentType: DocumentType
  detectedType: DocumentType | null
  hash: string
  validFrom: Date | null
  validUntil: Date | null
  linkedControlIds: string[]
  aiAnalysis: AIDocumentAnalysis | null
  status: EvidenceStatus
}

// =============================================================================
// CONTROL LIBRARY
// =============================================================================

export interface LocalizedString {
  de: string
  en: string
}

export interface FrameworkMapping {
  framework: string
  reference: string
}

export interface ApplicabilityCondition {
  field: string
  operator: ConditionOperator
  value: unknown
  result: ControlApplicability
  priority: number
}

export interface ControlLibraryEntry {
  id: string
  code: string
  category: ControlCategory
  type: 'TECHNICAL' | 'ORGANIZATIONAL'
  name: LocalizedString
  description: LocalizedString
  mappings: FrameworkMapping[]
  applicabilityConditions: ApplicabilityCondition[]
  defaultApplicability: ControlApplicability
  evidenceRequirements: string[]
  reviewFrequency: ReviewFrequency
  priority: ControlPriority
  complexity: ControlComplexity
  tags: string[]
}

// =============================================================================
// DERIVED TOM
// =============================================================================

export interface DerivedTOM {
  id: string
  controlId: string
  name: string
  description: string
  applicability: ControlApplicability
  applicabilityReason: string
  implementationStatus: ImplementationStatus
  responsiblePerson: string | null
  responsibleDepartment: string | null
  implementationDate: Date | null
  reviewDate: Date | null
  linkedEvidence: string[]
  evidenceGaps: string[]
  aiGeneratedDescription: string | null
  aiRecommendations: string[]
}

// =============================================================================
// GAP ANALYSIS
// =============================================================================

export interface MissingControl {
  controlId: string
  reason: string
  priority: string
}

export interface PartialControl {
  controlId: string
  missingAspects: string[]
}

export interface MissingEvidence {
  controlId: string
  requiredEvidence: string[]
}

export interface GapAnalysisResult {
  overallScore: number
  missingControls: MissingControl[]
  partialControls: PartialControl[]
  missingEvidence: MissingEvidence[]
  recommendations: string[]
  generatedAt: Date
}

// =============================================================================
// WIZARD STEP
// =============================================================================

export interface WizardStep {
  id: TOMGeneratorStepId
  completed: boolean
  data: unknown
  validatedAt: Date | null
}

// =============================================================================
// EXPORT RECORD
// =============================================================================

export interface ExportRecord {
  id: string
  format: 'DOCX' | 'PDF' | 'JSON' | 'ZIP'
  generatedAt: Date
  filename: string
}

// =============================================================================
// TOM GENERATOR STATE
// =============================================================================

export interface TOMGeneratorState {
  id: string
  tenantId: string
  companyProfile: CompanyProfile | null
  dataProfile: DataProfile | null
  architectureProfile: ArchitectureProfile | null
  securityProfile: SecurityProfile | null
  riskProfile: RiskProfile | null
  currentStep: TOMGeneratorStepId
  steps: WizardStep[]
  documents: EvidenceDocument[]
  derivedTOMs: DerivedTOM[]
  gapAnalysis: GapAnalysisResult | null
  exports: ExportRecord[]
  createdAt: Date
  updatedAt: Date
}

// =============================================================================
// RULES ENGINE TYPES
// =============================================================================

export interface RulesEngineResult {
  controlId: string
  applicability: ControlApplicability
  reason: string
  matchedCondition?: ApplicabilityCondition
}

export interface RulesEngineEvaluationContext {
  companyProfile: CompanyProfile | null
  dataProfile: DataProfile | null
  architectureProfile: ArchitectureProfile | null
  securityProfile: SecurityProfile | null
  riskProfile: RiskProfile | null
}

// =============================================================================
// API TYPES
// =============================================================================

export interface TOMGeneratorStateRequest {
  tenantId: string
}

export interface TOMGeneratorStateResponse {
  success: boolean
  state: TOMGeneratorState | null
  error?: string
}

export interface ControlsEvaluationRequest {
  tenantId: string
  context: RulesEngineEvaluationContext
}

export interface ControlsEvaluationResponse {
  success: boolean
  results: RulesEngineResult[]
  evaluatedAt: string
}

export interface EvidenceUploadRequest {
  tenantId: string
  documentType: DocumentType
  validFrom?: string
  validUntil?: string
}

export interface EvidenceUploadResponse {
  success: boolean
  document: EvidenceDocument | null
  error?: string
}

export interface EvidenceAnalyzeRequest {
  documentId: string
  tenantId: string
}

export interface EvidenceAnalyzeResponse {
  success: boolean
  analysis: AIDocumentAnalysis | null
  error?: string
}

export interface ExportRequest {
  tenantId: string
  format: 'DOCX' | 'PDF' | 'JSON' | 'ZIP'
  language: 'de' | 'en'
}

export interface ExportResponse {
  success: boolean
  exportId: string
  filename: string
  downloadUrl?: string
  error?: string
}

export interface GapAnalysisRequest {
  tenantId: string
}

export interface GapAnalysisResponse {
  success: boolean
  result: GapAnalysisResult | null
  error?: string
}

// =============================================================================
// STEP CONFIGURATION
// =============================================================================

export interface StepConfig {
  id: TOMGeneratorStepId
  title: LocalizedString
  description: LocalizedString
  checkpointId: string
  path: string
  /** Alias for path (for convenience) */
  url: string
  /** German title for display (for convenience) */
  name: string
}

export const TOM_GENERATOR_STEPS: StepConfig[] = [
  {
    id: 'scope-roles',
    title: { de: 'Scope & Rollen', en: 'Scope & Roles' },
    description: {
      de: 'Unternehmensname, Branche, Größe und Rolle definieren',
      en: 'Define company name, industry, size and role',
    },
    checkpointId: 'CP-TOM-SCOPE',
    path: '/sdk/tom-generator/scope',
    url: '/sdk/tom-generator/scope',
    name: 'Scope & Rollen',
  },
  {
    id: 'data-categories',
    title: { de: 'Datenkategorien', en: 'Data Categories' },
    description: {
      de: 'Datenkategorien und betroffene Personen erfassen',
      en: 'Capture data categories and data subjects',
    },
    checkpointId: 'CP-TOM-DATA',
    path: '/sdk/tom-generator/data',
    url: '/sdk/tom-generator/data',
    name: 'Datenkategorien',
  },
  {
    id: 'architecture-hosting',
    title: { de: 'Architektur & Hosting', en: 'Architecture & Hosting' },
    description: {
      de: 'Hosting-Modell, Standort und Provider definieren',
      en: 'Define hosting model, location and providers',
    },
    checkpointId: 'CP-TOM-ARCH',
    path: '/sdk/tom-generator/architecture',
    url: '/sdk/tom-generator/architecture',
    name: 'Architektur & Hosting',
  },
  {
    id: 'security-profile',
    title: { de: 'Security-Profil', en: 'Security Profile' },
    description: {
      de: 'Authentifizierung, Verschlüsselung und Backup konfigurieren',
      en: 'Configure authentication, encryption and backup',
    },
    checkpointId: 'CP-TOM-SEC',
    path: '/sdk/tom-generator/security',
    url: '/sdk/tom-generator/security',
    name: 'Security-Profil',
  },
  {
    id: 'risk-protection',
    title: { de: 'Risiko & Schutzbedarf', en: 'Risk & Protection Level' },
    description: {
      de: 'CIA-Bewertung und Schutzbedarf ermitteln',
      en: 'Determine CIA assessment and protection level',
    },
    checkpointId: 'CP-TOM-RISK',
    path: '/sdk/tom-generator/risk',
    url: '/sdk/tom-generator/risk',
    name: 'Risiko & Schutzbedarf',
  },
  {
    id: 'review-export',
    title: { de: 'Review & Export', en: 'Review & Export' },
    description: {
      de: 'Zusammenfassung prüfen und TOMs exportieren',
      en: 'Review summary and export TOMs',
    },
    checkpointId: 'CP-TOM-REVIEW',
    path: '/sdk/tom-generator/review',
    url: '/sdk/tom-generator/review',
    name: 'Review & Export',
  },
]

// =============================================================================
// CATEGORY METADATA
// =============================================================================

export interface CategoryMetadata {
  id: ControlCategory
  name: LocalizedString
  gdprReference: string
  icon?: string
}

export const CONTROL_CATEGORIES: CategoryMetadata[] = [
  {
    id: 'ACCESS_CONTROL',
    name: { de: 'Zutrittskontrolle', en: 'Physical Access Control' },
    gdprReference: 'Art. 32 Abs. 1 lit. b',
  },
  {
    id: 'ADMISSION_CONTROL',
    name: { de: 'Zugangskontrolle', en: 'System Access Control' },
    gdprReference: 'Art. 32 Abs. 1 lit. b',
  },
  {
    id: 'ACCESS_AUTHORIZATION',
    name: { de: 'Zugriffskontrolle', en: 'Access Authorization' },
    gdprReference: 'Art. 32 Abs. 1 lit. b',
  },
  {
    id: 'TRANSFER_CONTROL',
    name: { de: 'Weitergabekontrolle', en: 'Transfer Control' },
    gdprReference: 'Art. 32 Abs. 1 lit. b',
  },
  {
    id: 'INPUT_CONTROL',
    name: { de: 'Eingabekontrolle', en: 'Input Control' },
    gdprReference: 'Art. 32 Abs. 1 lit. b',
  },
  {
    id: 'ORDER_CONTROL',
    name: { de: 'Auftragskontrolle', en: 'Order Control' },
    gdprReference: 'Art. 28',
  },
  {
    id: 'AVAILABILITY',
    name: { de: 'Verfügbarkeit', en: 'Availability' },
    gdprReference: 'Art. 32 Abs. 1 lit. b, c',
  },
  {
    id: 'SEPARATION',
    name: { de: 'Trennbarkeit', en: 'Separation' },
    gdprReference: 'Art. 32 Abs. 1 lit. b',
  },
  {
    id: 'ENCRYPTION',
    name: { de: 'Verschlüsselung', en: 'Encryption' },
    gdprReference: 'Art. 32 Abs. 1 lit. a',
  },
  {
    id: 'PSEUDONYMIZATION',
    name: { de: 'Pseudonymisierung', en: 'Pseudonymization' },
    gdprReference: 'Art. 32 Abs. 1 lit. a',
  },
  {
    id: 'RESILIENCE',
    name: { de: 'Belastbarkeit', en: 'Resilience' },
    gdprReference: 'Art. 32 Abs. 1 lit. b',
  },
  {
    id: 'RECOVERY',
    name: { de: 'Wiederherstellbarkeit', en: 'Recovery' },
    gdprReference: 'Art. 32 Abs. 1 lit. c',
  },
  {
    id: 'REVIEW',
    name: { de: 'Überprüfung & Bewertung', en: 'Review & Assessment' },
    gdprReference: 'Art. 32 Abs. 1 lit. d',
  },
]

// =============================================================================
// DATA CATEGORY METADATA
// =============================================================================

export interface DataCategoryMetadata {
  id: DataCategory
  name: LocalizedString
  isSpecialCategory: boolean
  gdprReference?: string
}

export const DATA_CATEGORIES_METADATA: DataCategoryMetadata[] = [
  {
    id: 'IDENTIFICATION',
    name: { de: 'Identifikationsdaten', en: 'Identification Data' },
    isSpecialCategory: false,
  },
  {
    id: 'CONTACT',
    name: { de: 'Kontaktdaten', en: 'Contact Data' },
    isSpecialCategory: false,
  },
  {
    id: 'FINANCIAL',
    name: { de: 'Finanzdaten', en: 'Financial Data' },
    isSpecialCategory: false,
  },
  {
    id: 'PROFESSIONAL',
    name: { de: 'Berufliche Daten', en: 'Professional Data' },
    isSpecialCategory: false,
  },
  {
    id: 'LOCATION',
    name: { de: 'Standortdaten', en: 'Location Data' },
    isSpecialCategory: false,
  },
  {
    id: 'BEHAVIORAL',
    name: { de: 'Verhaltensdaten', en: 'Behavioral Data' },
    isSpecialCategory: false,
  },
  {
    id: 'BIOMETRIC',
    name: { de: 'Biometrische Daten', en: 'Biometric Data' },
    isSpecialCategory: true,
    gdprReference: 'Art. 9 Abs. 1',
  },
  {
    id: 'HEALTH',
    name: { de: 'Gesundheitsdaten', en: 'Health Data' },
    isSpecialCategory: true,
    gdprReference: 'Art. 9 Abs. 1',
  },
  {
    id: 'GENETIC',
    name: { de: 'Genetische Daten', en: 'Genetic Data' },
    isSpecialCategory: true,
    gdprReference: 'Art. 9 Abs. 1',
  },
  {
    id: 'POLITICAL',
    name: { de: 'Politische Meinungen', en: 'Political Opinions' },
    isSpecialCategory: true,
    gdprReference: 'Art. 9 Abs. 1',
  },
  {
    id: 'RELIGIOUS',
    name: { de: 'Religiöse Überzeugungen', en: 'Religious Beliefs' },
    isSpecialCategory: true,
    gdprReference: 'Art. 9 Abs. 1',
  },
  {
    id: 'SEXUAL_ORIENTATION',
    name: { de: 'Sexuelle Orientierung', en: 'Sexual Orientation' },
    isSpecialCategory: true,
    gdprReference: 'Art. 9 Abs. 1',
  },
  {
    id: 'CRIMINAL',
    name: { de: 'Strafrechtliche Daten', en: 'Criminal Data' },
    isSpecialCategory: true,
    gdprReference: 'Art. 10',
  },
]

// =============================================================================
// DATA SUBJECT METADATA
// =============================================================================

export interface DataSubjectMetadata {
  id: DataSubject
  name: LocalizedString
  isVulnerable: boolean
}

export const DATA_SUBJECTS_METADATA: DataSubjectMetadata[] = [
  {
    id: 'EMPLOYEES',
    name: { de: 'Mitarbeiter', en: 'Employees' },
    isVulnerable: false,
  },
  {
    id: 'CUSTOMERS',
    name: { de: 'Kunden', en: 'Customers' },
    isVulnerable: false,
  },
  {
    id: 'PROSPECTS',
    name: { de: 'Interessenten', en: 'Prospects' },
    isVulnerable: false,
  },
  {
    id: 'SUPPLIERS',
    name: { de: 'Lieferanten', en: 'Suppliers' },
    isVulnerable: false,
  },
  {
    id: 'MINORS',
    name: { de: 'Minderjährige', en: 'Minors' },
    isVulnerable: true,
  },
  {
    id: 'PATIENTS',
    name: { de: 'Patienten', en: 'Patients' },
    isVulnerable: true,
  },
  {
    id: 'STUDENTS',
    name: { de: 'Schüler/Studenten', en: 'Students' },
    isVulnerable: false,
  },
  {
    id: 'GENERAL_PUBLIC',
    name: { de: 'Allgemeine Öffentlichkeit', en: 'General Public' },
    isVulnerable: false,
  },
]

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

export function getStepByIndex(index: number): StepConfig | undefined {
  return TOM_GENERATOR_STEPS[index]
}

export function getStepById(id: TOMGeneratorStepId): StepConfig | undefined {
  return TOM_GENERATOR_STEPS.find((step) => step.id === id)
}

export function getStepIndex(id: TOMGeneratorStepId): number {
  return TOM_GENERATOR_STEPS.findIndex((step) => step.id === id)
}

export function getNextStep(
  currentId: TOMGeneratorStepId
): StepConfig | undefined {
  const currentIndex = getStepIndex(currentId)
  return TOM_GENERATOR_STEPS[currentIndex + 1]
}

export function getPreviousStep(
  currentId: TOMGeneratorStepId
): StepConfig | undefined {
  const currentIndex = getStepIndex(currentId)
  return currentIndex > 0 ? TOM_GENERATOR_STEPS[currentIndex - 1] : undefined
}

export function isSpecialCategory(category: DataCategory): boolean {
  const meta = DATA_CATEGORIES_METADATA.find((c) => c.id === category)
  return meta?.isSpecialCategory ?? false
}

export function hasSpecialCategories(categories: DataCategory[]): boolean {
  return categories.some(isSpecialCategory)
}

export function isVulnerableSubject(subject: DataSubject): boolean {
  const meta = DATA_SUBJECTS_METADATA.find((s) => s.id === subject)
  return meta?.isVulnerable ?? false
}

export function hasVulnerableSubjects(subjects: DataSubject[]): boolean {
  return subjects.some(isVulnerableSubject)
}

export function calculateProtectionLevel(
  ciaAssessment: CIAAssessment
): ProtectionLevel {
  const maxRating = Math.max(
    ciaAssessment.confidentiality,
    ciaAssessment.integrity,
    ciaAssessment.availability
  )

  if (maxRating >= 4) return 'VERY_HIGH'
  if (maxRating >= 3) return 'HIGH'
  return 'NORMAL'
}

export function isDSFARequired(
  dataProfile: DataProfile | null,
  riskProfile: RiskProfile | null
): boolean {
  if (!dataProfile) return false

  // DSFA required if:
  // 1. Special categories are processed
  if (dataProfile.hasSpecialCategories) return true

  // 2. Minors data is processed
  if (dataProfile.processesMinors) return true

  // 3. Large scale processing
  if (dataProfile.dataVolume === 'VERY_HIGH') return true

  // 4. High risk processing indicated
  if (riskProfile?.hasHighRiskProcessing) return true

  // 5. Very high protection level
  if (riskProfile?.protectionLevel === 'VERY_HIGH') return true

  return false
}

// =============================================================================
// INITIAL STATE FACTORY
// =============================================================================

export function createInitialTOMGeneratorState(
  tenantId: string
): TOMGeneratorState {
  const now = new Date()
  return {
    id: crypto.randomUUID(),
    tenantId,
    companyProfile: null,
    dataProfile: null,
    architectureProfile: null,
    securityProfile: null,
    riskProfile: null,
    currentStep: 'scope-roles',
    steps: TOM_GENERATOR_STEPS.map((step) => ({
      id: step.id,
      completed: false,
      data: null,
      validatedAt: null,
    })),
    documents: [],
    derivedTOMs: [],
    gapAnalysis: null,
    exports: [],
    createdAt: now,
    updatedAt: now,
  }
}

/**
 * Alias for createInitialTOMGeneratorState (for API compatibility)
 */
export const createEmptyTOMGeneratorState = createInitialTOMGeneratorState

// =============================================================================
// SDM TYPES (Standard-Datenschutzmodell)
// =============================================================================

export type SDMGewaehrleistungsziel =
  | 'Verfuegbarkeit'
  | 'Integritaet'
  | 'Vertraulichkeit'
  | 'Nichtverkettung'
  | 'Intervenierbarkeit'
  | 'Transparenz'
  | 'Datenminimierung'

export type TOMModuleCategory =
  | 'IDENTITY_AUTH'
  | 'LOGGING'
  | 'DOCUMENTATION'
  | 'SEPARATION'
  | 'RETENTION'
  | 'DELETION'
  | 'TRAINING'
  | 'REVIEW'

/**
 * Maps ControlCategory to SDM Gewaehrleistungsziele.
 * Used by the TOM Dashboard to display SDM coverage.
 */
export const SDM_CATEGORY_MAPPING: Record<ControlCategory, SDMGewaehrleistungsziel[]> = {
  ACCESS_CONTROL: ['Vertraulichkeit'],
  ADMISSION_CONTROL: ['Vertraulichkeit', 'Integritaet'],
  ACCESS_AUTHORIZATION: ['Vertraulichkeit', 'Nichtverkettung'],
  TRANSFER_CONTROL: ['Vertraulichkeit', 'Integritaet'],
  INPUT_CONTROL: ['Integritaet', 'Transparenz'],
  ORDER_CONTROL: ['Transparenz', 'Intervenierbarkeit'],
  AVAILABILITY: ['Verfuegbarkeit'],
  SEPARATION: ['Nichtverkettung', 'Datenminimierung'],
  ENCRYPTION: ['Vertraulichkeit', 'Integritaet'],
  PSEUDONYMIZATION: ['Datenminimierung', 'Nichtverkettung'],
  RESILIENCE: ['Verfuegbarkeit'],
  RECOVERY: ['Verfuegbarkeit', 'Integritaet'],
  REVIEW: ['Transparenz', 'Intervenierbarkeit'],
}

/**
 * Maps ControlCategory to Spec Module Categories.
 */
export const MODULE_CATEGORY_MAPPING: Record<ControlCategory, TOMModuleCategory[]> = {
  ACCESS_CONTROL: ['IDENTITY_AUTH'],
  ADMISSION_CONTROL: ['IDENTITY_AUTH'],
  ACCESS_AUTHORIZATION: ['IDENTITY_AUTH', 'DOCUMENTATION'],
  TRANSFER_CONTROL: ['DOCUMENTATION'],
  INPUT_CONTROL: ['LOGGING'],
  ORDER_CONTROL: ['DOCUMENTATION'],
  AVAILABILITY: ['REVIEW'],
  SEPARATION: ['SEPARATION'],
  ENCRYPTION: ['IDENTITY_AUTH'],
  PSEUDONYMIZATION: ['SEPARATION', 'DELETION'],
  RESILIENCE: ['REVIEW'],
  RECOVERY: ['REVIEW'],
  REVIEW: ['REVIEW', 'TRAINING'],
}
