/**
 * Helper Functions & Constants (Metadata)
 *
 * Utility functions for risk calculation, formatting, validation.
 * Localized metadata constants for enums (labels, articles, etc.).
 */

import type { LocalizedText } from './types-common'
import type {
  PersonalDataCategory,
  DataSubjectCategory,
  LegalBasisType,
  TransferMechanismType,
} from './types-processing'
import type {
  VendorRole,
  VendorStatus,
  ServiceCategory,
} from './types-vendor'
import type {
  DocumentType,
  ContractStatus,
} from './types-contract'
import type {
  FindingSeverity,
} from './types-finding'
import type {
  RiskLevel,
} from './types-risk'
import type {
  ProcessingActivityStatus,
} from './types-processing'

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

/**
 * Calculate risk level from score
 */
export function getRiskLevelFromScore(score: number): RiskLevel {
  if (score <= 4) return 'LOW'
  if (score <= 9) return 'MEDIUM'
  if (score <= 16) return 'HIGH'
  return 'CRITICAL'
}

/**
 * Calculate risk score from likelihood and impact
 */
export function calculateRiskScore(likelihood: number, impact: number): number {
  return likelihood * impact
}

/**
 * Check if data category is special (Art. 9 DSGVO)
 */
export function isSpecialCategory(category: PersonalDataCategory): boolean {
  const specialCategories: PersonalDataCategory[] = [
    'HEALTH_DATA',
    'GENETIC_DATA',
    'BIOMETRIC_DATA',
    'RACIAL_ETHNIC',
    'POLITICAL_OPINIONS',
    'RELIGIOUS_BELIEFS',
    'TRADE_UNION',
    'SEX_LIFE',
    'CRIMINAL_DATA',
  ]
  return specialCategories.includes(category)
}

/**
 * Check if country has adequacy decision
 */
export function hasAdequacyDecision(countryCode: string): boolean {
  const adequateCountries = [
    'AD', 'AR', 'CA', 'FO', 'GG', 'IL', 'IM', 'JP', 'JE', 'NZ', 'KR', 'CH', 'GB', 'UY',
    // EU/EEA countries
    'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU',
    'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE',
    'IS', 'LI', 'NO',
  ]
  return adequateCountries.includes(countryCode.toUpperCase())
}

/**
 * Generate VVT ID
 */
export function generateVVTId(existingIds: string[]): string {
  const year = new Date().getFullYear()
  const prefix = `VVT-${year}-`

  const existingNumbers = existingIds
    .filter(id => id.startsWith(prefix))
    .map(id => parseInt(id.replace(prefix, ''), 10))
    .filter(n => !isNaN(n))

  const nextNumber = existingNumbers.length > 0 ? Math.max(...existingNumbers) + 1 : 1
  return `${prefix}${nextNumber.toString().padStart(3, '0')}`
}

/**
 * Format date for display
 */
export function formatDate(date: Date | string | undefined): string {
  if (!date) return '-'
  const d = typeof date === 'string' ? new Date(date) : date
  return d.toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  })
}

/**
 * Get severity color class
 */
export function getSeverityColor(severity: FindingSeverity): string {
  switch (severity) {
    case 'LOW': return 'text-blue-600 bg-blue-100'
    case 'MEDIUM': return 'text-yellow-600 bg-yellow-100'
    case 'HIGH': return 'text-orange-600 bg-orange-100'
    case 'CRITICAL': return 'text-red-600 bg-red-100'
  }
}

/**
 * Get status color class
 */
export function getStatusColor(status: VendorStatus | ProcessingActivityStatus | ContractStatus): string {
  switch (status) {
    case 'ACTIVE':
    case 'APPROVED':
    case 'SIGNED':
      return 'text-green-600 bg-green-100'
    case 'DRAFT':
    case 'PENDING_REVIEW':
      return 'text-yellow-600 bg-yellow-100'
    case 'REVIEW':
    case 'INACTIVE':
      return 'text-blue-600 bg-blue-100'
    case 'ARCHIVED':
    case 'EXPIRED':
    case 'TERMINATED':
      return 'text-gray-600 bg-gray-100'
    default:
      return 'text-gray-600 bg-gray-100'
  }
}

// ==========================================
// CONSTANTS - METADATA
// ==========================================

export const DATA_SUBJECT_CATEGORY_META: Record<DataSubjectCategory, LocalizedText> = {
  EMPLOYEES: { de: 'Beschäftigte', en: 'Employees' },
  APPLICANTS: { de: 'Bewerber', en: 'Applicants' },
  CUSTOMERS: { de: 'Kunden', en: 'Customers' },
  PROSPECTIVE_CUSTOMERS: { de: 'Interessenten', en: 'Prospective Customers' },
  SUPPLIERS: { de: 'Lieferanten', en: 'Suppliers' },
  BUSINESS_PARTNERS: { de: 'Geschäftspartner', en: 'Business Partners' },
  VISITORS: { de: 'Besucher', en: 'Visitors' },
  WEBSITE_USERS: { de: 'Website-Nutzer', en: 'Website Users' },
  APP_USERS: { de: 'App-Nutzer', en: 'App Users' },
  NEWSLETTER_SUBSCRIBERS: { de: 'Newsletter-Abonnenten', en: 'Newsletter Subscribers' },
  MEMBERS: { de: 'Mitglieder', en: 'Members' },
  PATIENTS: { de: 'Patienten', en: 'Patients' },
  STUDENTS: { de: 'Schüler/Studenten', en: 'Students' },
  MINORS: { de: 'Minderjährige', en: 'Minors' },
  OTHER: { de: 'Sonstige', en: 'Other' },
}

export const PERSONAL_DATA_CATEGORY_META: Record<PersonalDataCategory, { label: LocalizedText; isSpecial: boolean }> = {
  NAME: { label: { de: 'Name', en: 'Name' }, isSpecial: false },
  CONTACT: { label: { de: 'Kontaktdaten', en: 'Contact Data' }, isSpecial: false },
  ADDRESS: { label: { de: 'Adressdaten', en: 'Address Data' }, isSpecial: false },
  DOB: { label: { de: 'Geburtsdatum', en: 'Date of Birth' }, isSpecial: false },
  ID_NUMBER: { label: { de: 'Ausweisnummern', en: 'ID Numbers' }, isSpecial: false },
  SOCIAL_SECURITY: { label: { de: 'Sozialversicherungsnummer', en: 'Social Security Number' }, isSpecial: false },
  TAX_ID: { label: { de: 'Steuer-ID', en: 'Tax ID' }, isSpecial: false },
  BANK_ACCOUNT: { label: { de: 'Bankverbindung', en: 'Bank Account' }, isSpecial: false },
  PAYMENT_DATA: { label: { de: 'Zahlungsdaten', en: 'Payment Data' }, isSpecial: false },
  EMPLOYMENT_DATA: { label: { de: 'Beschäftigungsdaten', en: 'Employment Data' }, isSpecial: false },
  SALARY_DATA: { label: { de: 'Gehaltsdaten', en: 'Salary Data' }, isSpecial: false },
  EDUCATION_DATA: { label: { de: 'Bildungsdaten', en: 'Education Data' }, isSpecial: false },
  PHOTO_VIDEO: { label: { de: 'Fotos/Videos', en: 'Photos/Videos' }, isSpecial: false },
  IP_ADDRESS: { label: { de: 'IP-Adressen', en: 'IP Addresses' }, isSpecial: false },
  DEVICE_ID: { label: { de: 'Gerätekennungen', en: 'Device IDs' }, isSpecial: false },
  LOCATION_DATA: { label: { de: 'Standortdaten', en: 'Location Data' }, isSpecial: false },
  USAGE_DATA: { label: { de: 'Nutzungsdaten', en: 'Usage Data' }, isSpecial: false },
  COMMUNICATION_DATA: { label: { de: 'Kommunikationsdaten', en: 'Communication Data' }, isSpecial: false },
  CONTRACT_DATA: { label: { de: 'Vertragsdaten', en: 'Contract Data' }, isSpecial: false },
  LOGIN_DATA: { label: { de: 'Login-Daten', en: 'Login Data' }, isSpecial: false },
  HEALTH_DATA: { label: { de: 'Gesundheitsdaten', en: 'Health Data' }, isSpecial: true },
  GENETIC_DATA: { label: { de: 'Genetische Daten', en: 'Genetic Data' }, isSpecial: true },
  BIOMETRIC_DATA: { label: { de: 'Biometrische Daten', en: 'Biometric Data' }, isSpecial: true },
  RACIAL_ETHNIC: { label: { de: 'Rassische/Ethnische Herkunft', en: 'Racial/Ethnic Origin' }, isSpecial: true },
  POLITICAL_OPINIONS: { label: { de: 'Politische Meinungen', en: 'Political Opinions' }, isSpecial: true },
  RELIGIOUS_BELIEFS: { label: { de: 'Religiöse Überzeugungen', en: 'Religious Beliefs' }, isSpecial: true },
  TRADE_UNION: { label: { de: 'Gewerkschaftszugehörigkeit', en: 'Trade Union Membership' }, isSpecial: true },
  SEX_LIFE: { label: { de: 'Sexualleben/Orientierung', en: 'Sex Life/Orientation' }, isSpecial: true },
  CRIMINAL_DATA: { label: { de: 'Strafrechtliche Daten', en: 'Criminal Data' }, isSpecial: true },
  OTHER: { label: { de: 'Sonstige', en: 'Other' }, isSpecial: false },
}

export const LEGAL_BASIS_META: Record<LegalBasisType, { label: LocalizedText; article: string }> = {
  CONSENT: { label: { de: 'Einwilligung', en: 'Consent' }, article: 'Art. 6 Abs. 1 lit. a DSGVO' },
  CONTRACT: { label: { de: 'Vertragserfüllung', en: 'Contract Performance' }, article: 'Art. 6 Abs. 1 lit. b DSGVO' },
  LEGAL_OBLIGATION: { label: { de: 'Rechtliche Verpflichtung', en: 'Legal Obligation' }, article: 'Art. 6 Abs. 1 lit. c DSGVO' },
  VITAL_INTEREST: { label: { de: 'Lebenswichtige Interessen', en: 'Vital Interests' }, article: 'Art. 6 Abs. 1 lit. d DSGVO' },
  PUBLIC_TASK: { label: { de: 'Öffentliche Aufgabe', en: 'Public Task' }, article: 'Art. 6 Abs. 1 lit. e DSGVO' },
  LEGITIMATE_INTEREST: { label: { de: 'Berechtigtes Interesse', en: 'Legitimate Interest' }, article: 'Art. 6 Abs. 1 lit. f DSGVO' },
  ART9_CONSENT: { label: { de: 'Ausdrückliche Einwilligung', en: 'Explicit Consent' }, article: 'Art. 9 Abs. 2 lit. a DSGVO' },
  ART9_EMPLOYMENT: { label: { de: 'Arbeitsrecht', en: 'Employment Law' }, article: 'Art. 9 Abs. 2 lit. b DSGVO' },
  ART9_VITAL_INTEREST: { label: { de: 'Lebenswichtige Interessen', en: 'Vital Interests' }, article: 'Art. 9 Abs. 2 lit. c DSGVO' },
  ART9_FOUNDATION: { label: { de: 'Stiftung/Verein', en: 'Foundation/Association' }, article: 'Art. 9 Abs. 2 lit. d DSGVO' },
  ART9_PUBLIC: { label: { de: 'Offenkundig öffentlich', en: 'Manifestly Public' }, article: 'Art. 9 Abs. 2 lit. e DSGVO' },
  ART9_LEGAL_CLAIMS: { label: { de: 'Rechtsansprüche', en: 'Legal Claims' }, article: 'Art. 9 Abs. 2 lit. f DSGVO' },
  ART9_PUBLIC_INTEREST: { label: { de: 'Öffentliches Interesse', en: 'Public Interest' }, article: 'Art. 9 Abs. 2 lit. g DSGVO' },
  ART9_HEALTH: { label: { de: 'Gesundheitsversorgung', en: 'Health Care' }, article: 'Art. 9 Abs. 2 lit. h DSGVO' },
  ART9_PUBLIC_HEALTH: { label: { de: 'Öffentliche Gesundheit', en: 'Public Health' }, article: 'Art. 9 Abs. 2 lit. i DSGVO' },
  ART9_ARCHIVING: { label: { de: 'Archivzwecke', en: 'Archiving Purposes' }, article: 'Art. 9 Abs. 2 lit. j DSGVO' },
}

export const VENDOR_ROLE_META: Record<VendorRole, LocalizedText> = {
  PROCESSOR: { de: 'Auftragsverarbeiter', en: 'Processor' },
  JOINT_CONTROLLER: { de: 'Gemeinsam Verantwortlicher', en: 'Joint Controller' },
  CONTROLLER: { de: 'Eigenständiger Verantwortlicher', en: 'Independent Controller' },
  SUB_PROCESSOR: { de: 'Unterauftragnehmer', en: 'Sub-Processor' },
  THIRD_PARTY: { de: 'Dritter', en: 'Third Party' },
}

export const SERVICE_CATEGORY_META: Record<ServiceCategory, LocalizedText> = {
  HOSTING: { de: 'Hosting', en: 'Hosting' },
  CLOUD_INFRASTRUCTURE: { de: 'Cloud-Infrastruktur', en: 'Cloud Infrastructure' },
  ANALYTICS: { de: 'Analytics', en: 'Analytics' },
  CRM: { de: 'CRM', en: 'CRM' },
  ERP: { de: 'ERP', en: 'ERP' },
  HR_SOFTWARE: { de: 'HR-Software', en: 'HR Software' },
  PAYMENT: { de: 'Zahlungsabwicklung', en: 'Payment Processing' },
  EMAIL: { de: 'E-Mail', en: 'Email' },
  MARKETING: { de: 'Marketing', en: 'Marketing' },
  SUPPORT: { de: 'Support', en: 'Support' },
  SECURITY: { de: 'Sicherheit', en: 'Security' },
  INTEGRATION: { de: 'Integration', en: 'Integration' },
  CONSULTING: { de: 'Beratung', en: 'Consulting' },
  LEGAL: { de: 'Rechtliches', en: 'Legal' },
  ACCOUNTING: { de: 'Buchhaltung', en: 'Accounting' },
  COMMUNICATION: { de: 'Kommunikation', en: 'Communication' },
  STORAGE: { de: 'Speicher', en: 'Storage' },
  BACKUP: { de: 'Backup', en: 'Backup' },
  CDN: { de: 'CDN', en: 'CDN' },
  OTHER: { de: 'Sonstige', en: 'Other' },
}

export const DOCUMENT_TYPE_META: Record<DocumentType, LocalizedText> = {
  AVV: { de: 'Auftragsverarbeitungsvertrag', en: 'Data Processing Agreement' },
  MSA: { de: 'Rahmenvertrag', en: 'Master Service Agreement' },
  SLA: { de: 'Service Level Agreement', en: 'Service Level Agreement' },
  SCC: { de: 'Standardvertragsklauseln', en: 'Standard Contractual Clauses' },
  NDA: { de: 'Geheimhaltungsvereinbarung', en: 'Non-Disclosure Agreement' },
  TOM_ANNEX: { de: 'TOM-Anlage', en: 'TOM Annex' },
  CERTIFICATION: { de: 'Zertifikat', en: 'Certification' },
  SUB_PROCESSOR_LIST: { de: 'Unterauftragnehmer-Liste', en: 'Sub-Processor List' },
  OTHER: { de: 'Sonstige', en: 'Other' },
}

export const TRANSFER_MECHANISM_META: Record<TransferMechanismType, LocalizedText> = {
  ADEQUACY_DECISION: { de: 'Angemessenheitsbeschluss', en: 'Adequacy Decision' },
  SCC_CONTROLLER: { de: 'SCC (Controller-to-Controller)', en: 'SCC (Controller-to-Controller)' },
  SCC_PROCESSOR: { de: 'SCC (Controller-to-Processor)', en: 'SCC (Controller-to-Processor)' },
  BCR: { de: 'Binding Corporate Rules', en: 'Binding Corporate Rules' },
  DEROGATION_CONSENT: { de: 'Ausdrückliche Einwilligung', en: 'Explicit Consent' },
  DEROGATION_CONTRACT: { de: 'Vertragserfüllung', en: 'Contract Performance' },
  DEROGATION_LEGAL: { de: 'Rechtsansprüche', en: 'Legal Claims' },
  DEROGATION_PUBLIC: { de: 'Öffentliches Interesse', en: 'Public Interest' },
  CERTIFICATION: { de: 'Zertifizierung', en: 'Certification' },
  CODE_OF_CONDUCT: { de: 'Verhaltensregeln', en: 'Code of Conduct' },
}
