/**
 * DSFA Types - Datenschutz-Folgenabschätzung (Art. 35 DSGVO)
 *
 * TypeScript type definitions for DSFA (Data Protection Impact Assessment)
 * aligned with the backend Go models.
 */

// =============================================================================
// ENUMS & CONSTANTS
// =============================================================================

export type DSFAStatus = 'draft' | 'in_review' | 'approved' | 'rejected' | 'needs_update'

export type DSFARiskLevel = 'low' | 'medium' | 'high' | 'very_high'

export type DSFARiskCategory = 'confidentiality' | 'integrity' | 'availability' | 'rights_freedoms'

export type DSFAMitigationType = 'technical' | 'organizational' | 'legal'

export type DSFAMitigationStatus = 'planned' | 'in_progress' | 'implemented' | 'verified'

export const DSFA_STATUS_LABELS: Record<DSFAStatus, string> = {
  draft: 'Entwurf',
  in_review: 'In Prüfung',
  approved: 'Genehmigt',
  rejected: 'Abgelehnt',
  needs_update: 'Überarbeitung erforderlich',
}

export const DSFA_RISK_LEVEL_LABELS: Record<DSFARiskLevel, string> = {
  low: 'Niedrig',
  medium: 'Mittel',
  high: 'Hoch',
  very_high: 'Sehr Hoch',
}

export const DSFA_LEGAL_BASES = {
  consent: 'Art. 6 Abs. 1 lit. a DSGVO - Einwilligung',
  contract: 'Art. 6 Abs. 1 lit. b DSGVO - Vertrag',
  legal_obligation: 'Art. 6 Abs. 1 lit. c DSGVO - Rechtliche Verpflichtung',
  vital_interests: 'Art. 6 Abs. 1 lit. d DSGVO - Lebenswichtige Interessen',
  public_interest: 'Art. 6 Abs. 1 lit. e DSGVO - Öffentliches Interesse',
  legitimate_interest: 'Art. 6 Abs. 1 lit. f DSGVO - Berechtigtes Interesse',
}

export const DSFA_AFFECTED_RIGHTS = [
  { id: 'right_to_information', label: 'Recht auf Information (Art. 13/14)' },
  { id: 'right_of_access', label: 'Auskunftsrecht (Art. 15)' },
  { id: 'right_to_rectification', label: 'Recht auf Berichtigung (Art. 16)' },
  { id: 'right_to_erasure', label: 'Recht auf Löschung (Art. 17)' },
  { id: 'right_to_restriction', label: 'Recht auf Einschränkung (Art. 18)' },
  { id: 'right_to_data_portability', label: 'Recht auf Datenübertragbarkeit (Art. 20)' },
  { id: 'right_to_object', label: 'Widerspruchsrecht (Art. 21)' },
  { id: 'right_not_to_be_profiled', label: 'Recht bzgl. Profiling (Art. 22)' },
  { id: 'freedom_of_expression', label: 'Meinungsfreiheit' },
  { id: 'freedom_of_association', label: 'Versammlungsfreiheit' },
  { id: 'non_discrimination', label: 'Nichtdiskriminierung' },
  { id: 'data_security', label: 'Datensicherheit' },
]

// =============================================================================
// SUB-TYPES
// =============================================================================

export interface DSFARisk {
  id: string
  category: DSFARiskCategory
  description: string
  likelihood: 'low' | 'medium' | 'high'
  impact: 'low' | 'medium' | 'high'
  risk_level: string
  affected_data: string[]
}

export interface DSFAMitigation {
  id: string
  risk_id: string
  description: string
  type: DSFAMitigationType
  status: DSFAMitigationStatus
  implemented_at?: string
  verified_at?: string
  residual_risk: 'low' | 'medium' | 'high'
  tom_reference?: string
  responsible_party: string
}

export interface DSFAReviewComment {
  id: string
  section: number
  comment: string
  created_by: string
  created_at: string
  resolved: boolean
}

export interface DSFASectionProgress {
  section_1_complete: boolean
  section_2_complete: boolean
  section_3_complete: boolean
  section_4_complete: boolean
  section_5_complete: boolean
}

// =============================================================================
// MAIN DSFA TYPE
// =============================================================================

export interface DSFA {
  id: string
  tenant_id: string
  namespace_id?: string
  processing_activity_id?: string
  assessment_id?: string
  name: string
  description: string

  // Section 1: Systematische Beschreibung (Art. 35 Abs. 7 lit. a)
  processing_description: string
  processing_purpose: string
  data_categories: string[]
  data_subjects: string[]
  recipients: string[]
  legal_basis: string
  legal_basis_details?: string

  // Section 2: Notwendigkeit & Verhältnismäßigkeit (Art. 35 Abs. 7 lit. b)
  necessity_assessment: string
  proportionality_assessment: string
  data_minimization?: string
  alternatives_considered?: string
  retention_justification?: string

  // Section 3: Risikobewertung (Art. 35 Abs. 7 lit. c)
  risks: DSFARisk[]
  overall_risk_level: DSFARiskLevel
  risk_score: number
  affected_rights?: string[]
  triggered_rule_codes?: string[]

  // Section 4: Abhilfemaßnahmen (Art. 35 Abs. 7 lit. d)
  mitigations: DSFAMitigation[]
  tom_references?: string[]

  // Section 5: Stellungnahme DSB (Art. 35 Abs. 2 + Art. 36)
  dpo_consulted: boolean
  dpo_consulted_at?: string
  dpo_name?: string
  dpo_opinion?: string
  dpo_approved?: boolean
  authority_consulted: boolean
  authority_consulted_at?: string
  authority_reference?: string
  authority_decision?: string

  // Workflow & Approval
  status: DSFAStatus
  submitted_for_review_at?: string
  submitted_by?: string
  conclusion: string
  review_comments?: DSFAReviewComment[]

  // Section Progress Tracking
  section_progress: DSFASectionProgress

  // Metadata & Audit
  metadata?: Record<string, unknown>
  created_at: string
  updated_at: string
  created_by: string
  approved_by?: string
  approved_at?: string
}

// =============================================================================
// API REQUEST/RESPONSE TYPES
// =============================================================================

export interface DSFAListResponse {
  dsfas: DSFA[]
}

export interface DSFAStatsResponse {
  status_stats: Record<DSFAStatus | 'total', number>
  risk_stats: Record<DSFARiskLevel, number>
  total: number
}

export interface CreateDSFARequest {
  name: string
  description?: string
  processing_description?: string
  processing_purpose?: string
  data_categories?: string[]
  legal_basis?: string
}

export interface CreateDSFAFromAssessmentRequest {
  name?: string
  description?: string
}

export interface CreateDSFAFromAssessmentResponse {
  dsfa: DSFA
  prefilled: boolean
  assessment: unknown // UCCA Assessment
  message: string
}

export interface UpdateDSFASectionRequest {
  // Section 1
  processing_description?: string
  processing_purpose?: string
  data_categories?: string[]
  data_subjects?: string[]
  recipients?: string[]
  legal_basis?: string
  legal_basis_details?: string

  // Section 2
  necessity_assessment?: string
  proportionality_assessment?: string
  data_minimization?: string
  alternatives_considered?: string
  retention_justification?: string

  // Section 3
  overall_risk_level?: DSFARiskLevel
  risk_score?: number
  affected_rights?: string[]

  // Section 5
  dpo_consulted?: boolean
  dpo_name?: string
  dpo_opinion?: string
  authority_consulted?: boolean
  authority_reference?: string
  authority_decision?: string
}

export interface SubmitForReviewResponse {
  message: string
  dsfa: DSFA
}

export interface ApproveDSFARequest {
  dpo_opinion: string
  approved: boolean
}

// =============================================================================
// UCCA INTEGRATION TYPES
// =============================================================================

export interface DSFATriggerInfo {
  required: boolean
  reason: string
  triggered_rules: string[]
  assessment_id?: string
  existing_dsfa_id?: string
}

export interface UCCATriggeredRule {
  code: string
  title: string
  description: string
  severity: 'INFO' | 'WARN' | 'BLOCK'
  gdpr_ref?: string
}

// =============================================================================
// HELPER TYPES FOR UI
// =============================================================================

export interface DSFASectionConfig {
  number: number
  title: string
  titleDE: string
  description: string
  gdprRef: string
  fields: string[]
  required: boolean
}

export const DSFA_SECTIONS: DSFASectionConfig[] = [
  {
    number: 1,
    title: 'Processing Description',
    titleDE: 'Systematische Beschreibung',
    description: 'Beschreiben Sie die geplante Verarbeitung, ihren Zweck, die Datenkategorien und Rechtsgrundlage.',
    gdprRef: 'Art. 35 Abs. 7 lit. a DSGVO',
    fields: ['processing_description', 'processing_purpose', 'data_categories', 'data_subjects', 'recipients', 'legal_basis'],
    required: true,
  },
  {
    number: 2,
    title: 'Necessity & Proportionality',
    titleDE: 'Notwendigkeit & Verhältnismäßigkeit',
    description: 'Begründen Sie, warum die Verarbeitung notwendig ist und welche Alternativen geprüft wurden.',
    gdprRef: 'Art. 35 Abs. 7 lit. b DSGVO',
    fields: ['necessity_assessment', 'proportionality_assessment', 'data_minimization', 'alternatives_considered'],
    required: true,
  },
  {
    number: 3,
    title: 'Risk Assessment',
    titleDE: 'Risikobewertung',
    description: 'Identifizieren und bewerten Sie die Risiken für die Rechte und Freiheiten der Betroffenen.',
    gdprRef: 'Art. 35 Abs. 7 lit. c DSGVO',
    fields: ['risks', 'overall_risk_level', 'risk_score', 'affected_rights'],
    required: true,
  },
  {
    number: 4,
    title: 'Mitigation Measures',
    titleDE: 'Abhilfemaßnahmen',
    description: 'Definieren Sie technische und organisatorische Maßnahmen zur Risikominimierung.',
    gdprRef: 'Art. 35 Abs. 7 lit. d DSGVO',
    fields: ['mitigations', 'tom_references'],
    required: true,
  },
  {
    number: 5,
    title: 'DPO Opinion',
    titleDE: 'Stellungnahme DSB',
    description: 'Dokumentieren Sie die Konsultation des Datenschutzbeauftragten und ggf. der Aufsichtsbehörde.',
    gdprRef: 'Art. 35 Abs. 2 + Art. 36 DSGVO',
    fields: ['dpo_consulted', 'dpo_opinion', 'authority_consulted', 'authority_reference'],
    required: false,
  },
]

// =============================================================================
// RISK MATRIX HELPERS
// =============================================================================

export interface RiskMatrixCell {
  likelihood: 'low' | 'medium' | 'high'
  impact: 'low' | 'medium' | 'high'
  level: DSFARiskLevel
  score: number
}

export const RISK_MATRIX: RiskMatrixCell[] = [
  // Low likelihood
  { likelihood: 'low', impact: 'low', level: 'low', score: 10 },
  { likelihood: 'low', impact: 'medium', level: 'low', score: 20 },
  { likelihood: 'low', impact: 'high', level: 'medium', score: 40 },
  // Medium likelihood
  { likelihood: 'medium', impact: 'low', level: 'low', score: 20 },
  { likelihood: 'medium', impact: 'medium', level: 'medium', score: 50 },
  { likelihood: 'medium', impact: 'high', level: 'high', score: 70 },
  // High likelihood
  { likelihood: 'high', impact: 'low', level: 'medium', score: 40 },
  { likelihood: 'high', impact: 'medium', level: 'high', score: 70 },
  { likelihood: 'high', impact: 'high', level: 'very_high', score: 90 },
]

export function calculateRiskLevel(
  likelihood: 'low' | 'medium' | 'high',
  impact: 'low' | 'medium' | 'high'
): { level: DSFARiskLevel; score: number } {
  const cell = RISK_MATRIX.find(c => c.likelihood === likelihood && c.impact === impact)
  return cell ? { level: cell.level, score: cell.score } : { level: 'medium', score: 50 }
}
