// =============================================================================
// TOM Generator Demo Data
// Sample data for demonstration and testing
// =============================================================================

import {
  TOMGeneratorState,
  CompanyProfile,
  DataProfile,
  ArchitectureProfile,
  SecurityProfile,
  TOM_GENERATOR_STEPS,
} from '../types'
import { getTOMRulesEngine } from '../rules-engine'
import { DEMO_RISK_PROFILES, DEMO_EVIDENCE_DOCUMENTS } from './demo-data-part2'

// Re-export risk profiles and evidence from part2 for backward compatibility
export { DEMO_RISK_PROFILES, DEMO_EVIDENCE_DOCUMENTS } from './demo-data-part2'

// =============================================================================
// DEMO COMPANY PROFILES
// =============================================================================

export const DEMO_COMPANY_PROFILES: Record<string, CompanyProfile> = {
  saas: {
    id: 'demo-company-saas',
    name: 'CloudTech Solutions GmbH',
    industry: 'Software / SaaS',
    size: 'MEDIUM',
    role: 'PROCESSOR',
    products: ['Cloud CRM', 'Analytics Platform', 'API Services'],
    dpoPerson: 'Dr. Maria Schmidt',
    dpoEmail: 'dpo@cloudtech.de',
    itSecurityContact: 'Thomas Müller',
  },
  healthcare: {
    id: 'demo-company-health',
    name: 'MediCare Digital GmbH',
    industry: 'Gesundheitswesen / HealthTech',
    size: 'SMALL',
    role: 'CONTROLLER',
    products: ['Patientenportal', 'Telemedizin-App', 'Terminbuchung'],
    dpoPerson: 'Dr. Klaus Weber',
    dpoEmail: 'datenschutz@medicare.de',
    itSecurityContact: 'Anna Bauer',
  },
  enterprise: {
    id: 'demo-company-enterprise',
    name: 'GlobalCorp AG',
    industry: 'Finanzdienstleistungen',
    size: 'ENTERPRISE',
    role: 'CONTROLLER',
    products: ['Online Banking', 'Investment Platform', 'Payment Services'],
    dpoPerson: 'Prof. Dr. Hans Meyer',
    dpoEmail: 'privacy@globalcorp.de',
    itSecurityContact: 'Security Team',
  },
}

// =============================================================================
// DEMO DATA PROFILES
// =============================================================================

export const DEMO_DATA_PROFILES: Record<string, DataProfile> = {
  saas: {
    categories: ['IDENTIFICATION', 'CONTACT', 'PROFESSIONAL', 'BEHAVIORAL'],
    subjects: ['CUSTOMERS', 'EMPLOYEES'],
    hasSpecialCategories: false,
    processesMinors: false,
    dataVolume: 'HIGH',
    thirdCountryTransfers: true,
    thirdCountryList: ['USA'],
  },
  healthcare: {
    categories: ['IDENTIFICATION', 'CONTACT', 'HEALTH', 'BIOMETRIC'],
    subjects: ['PATIENTS', 'EMPLOYEES'],
    hasSpecialCategories: true,
    processesMinors: true,
    dataVolume: 'MEDIUM',
    thirdCountryTransfers: false,
    thirdCountryList: [],
  },
  enterprise: {
    categories: ['IDENTIFICATION', 'CONTACT', 'FINANCIAL', 'BEHAVIORAL'],
    subjects: ['CUSTOMERS', 'EMPLOYEES', 'PROSPECTS'],
    hasSpecialCategories: false,
    processesMinors: false,
    dataVolume: 'VERY_HIGH',
    thirdCountryTransfers: true,
    thirdCountryList: ['USA', 'UK', 'Schweiz'],
  },
}

// =============================================================================
// DEMO ARCHITECTURE PROFILES
// =============================================================================

export const DEMO_ARCHITECTURE_PROFILES: Record<string, ArchitectureProfile> = {
  saas: {
    hostingModel: 'PUBLIC_CLOUD',
    hostingLocation: 'EU',
    providers: [
      { name: 'AWS', location: 'EU', certifications: ['ISO 27001', 'SOC 2', 'C5'] },
      { name: 'Cloudflare', location: 'EU', certifications: ['ISO 27001'] },
    ],
    multiTenancy: 'MULTI_TENANT',
    hasSubprocessors: true,
    subprocessorCount: 5,
    encryptionAtRest: true,
    encryptionInTransit: true,
  },
  healthcare: {
    hostingModel: 'PRIVATE_CLOUD',
    hostingLocation: 'DE',
    providers: [
      { name: 'Telekom Cloud', location: 'DE', certifications: ['ISO 27001', 'C5', 'TISAX'] },
    ],
    multiTenancy: 'SINGLE_TENANT',
    hasSubprocessors: true,
    subprocessorCount: 2,
    encryptionAtRest: true,
    encryptionInTransit: true,
  },
  enterprise: {
    hostingModel: 'HYBRID',
    hostingLocation: 'DE',
    providers: [
      { name: 'Private Datacenter', location: 'DE', certifications: ['ISO 27001', 'SOC 2'] },
      { name: 'Azure', location: 'EU', certifications: ['ISO 27001', 'C5', 'SOC 2'] },
    ],
    multiTenancy: 'DEDICATED',
    hasSubprocessors: true,
    subprocessorCount: 10,
    encryptionAtRest: true,
    encryptionInTransit: true,
  },
}

// =============================================================================
// DEMO SECURITY PROFILES
// =============================================================================

export const DEMO_SECURITY_PROFILES: Record<string, SecurityProfile> = {
  saas: {
    authMethods: [
      { type: 'PASSWORD', provider: null },
      { type: 'MFA', provider: 'Auth0' },
      { type: 'SSO', provider: 'Auth0' },
    ],
    hasMFA: true,
    hasSSO: true,
    hasIAM: true,
    hasPAM: false,
    hasEncryptionAtRest: true,
    hasEncryptionInTransit: true,
    hasLogging: true,
    logRetentionDays: 90,
    hasBackup: true,
    backupFrequency: 'DAILY',
    backupRetentionDays: 30,
    hasDRPlan: true,
    rtoHours: 4,
    rpoHours: 1,
    hasVulnerabilityManagement: true,
    hasPenetrationTests: true,
    hasSecurityTraining: true,
  },
  healthcare: {
    authMethods: [
      { type: 'PASSWORD', provider: null },
      { type: 'MFA', provider: 'Microsoft Authenticator' },
      { type: 'CERTIFICATE', provider: 'Internal PKI' },
    ],
    hasMFA: true,
    hasSSO: false,
    hasIAM: true,
    hasPAM: true,
    hasEncryptionAtRest: true,
    hasEncryptionInTransit: true,
    hasLogging: true,
    logRetentionDays: 365,
    hasBackup: true,
    backupFrequency: 'HOURLY',
    backupRetentionDays: 90,
    hasDRPlan: true,
    rtoHours: 2,
    rpoHours: 0.5,
    hasVulnerabilityManagement: true,
    hasPenetrationTests: true,
    hasSecurityTraining: true,
  },
  enterprise: {
    authMethods: [
      { type: 'PASSWORD', provider: null },
      { type: 'MFA', provider: 'Okta' },
      { type: 'SSO', provider: 'Okta' },
      { type: 'BIOMETRIC', provider: 'Windows Hello' },
    ],
    hasMFA: true,
    hasSSO: true,
    hasIAM: true,
    hasPAM: true,
    hasEncryptionAtRest: true,
    hasEncryptionInTransit: true,
    hasLogging: true,
    logRetentionDays: 730,
    hasBackup: true,
    backupFrequency: 'HOURLY',
    backupRetentionDays: 365,
    hasDRPlan: true,
    rtoHours: 1,
    rpoHours: 0.25,
    hasVulnerabilityManagement: true,
    hasPenetrationTests: true,
    hasSecurityTraining: true,
  },
}

// =============================================================================
// DEMO STATE GENERATOR
// =============================================================================

export type DemoScenario = 'saas' | 'healthcare' | 'enterprise'

/**
 * Generate a complete demo state for a given scenario
 */
export function generateDemoState(
  tenantId: string,
  scenario: DemoScenario = 'saas'
): TOMGeneratorState {
  const companyProfile = DEMO_COMPANY_PROFILES[scenario]
  const dataProfile = DEMO_DATA_PROFILES[scenario]
  const architectureProfile = DEMO_ARCHITECTURE_PROFILES[scenario]
  const securityProfile = DEMO_SECURITY_PROFILES[scenario]
  const riskProfile = DEMO_RISK_PROFILES[scenario]

  // Generate derived TOMs using the rules engine
  const rulesEngine = getTOMRulesEngine()
  const derivedTOMs = rulesEngine.deriveAllTOMs({
    companyProfile,
    dataProfile,
    architectureProfile,
    securityProfile,
    riskProfile,
  })

  // Set some TOMs as implemented for demo
  const implementedTOMs = derivedTOMs.map((tom, index) => ({
    ...tom,
    implementationStatus:
      index % 3 === 0
        ? 'IMPLEMENTED' as const
        : index % 3 === 1
          ? 'PARTIAL' as const
          : 'NOT_IMPLEMENTED' as const,
    responsiblePerson:
      index % 2 === 0 ? 'IT Security Team' : 'Datenschutzbeauftragter',
    implementationDate:
      index % 3 === 0 ? new Date('2024-06-15') : null,
  }))

  // Generate gap analysis
  const gapAnalysis = rulesEngine.performGapAnalysis(
    implementedTOMs,
    DEMO_EVIDENCE_DOCUMENTS
  )

  const now = new Date()

  return {
    id: `demo-state-${scenario}-${Date.now()}`,
    tenantId,
    companyProfile,
    dataProfile,
    architectureProfile,
    securityProfile,
    riskProfile,
    currentStep: 'review-export',
    steps: TOM_GENERATOR_STEPS.map((step) => ({
      id: step.id,
      completed: true,
      data: null,
      validatedAt: now,
    })),
    documents: DEMO_EVIDENCE_DOCUMENTS,
    derivedTOMs: implementedTOMs,
    gapAnalysis,
    exports: [],
    createdAt: now,
    updatedAt: now,
  }
}

/**
 * Generate an empty starter state
 */
export function generateEmptyState(tenantId: string): TOMGeneratorState {
  const now = new Date()

  return {
    id: `new-state-${Date.now()}`,
    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,
  }
}

/**
 * Generate partial state (first 3 steps completed)
 */
export function generatePartialState(
  tenantId: string,
  scenario: DemoScenario = 'saas'
): TOMGeneratorState {
  const state = generateEmptyState(tenantId)
  const now = new Date()

  state.companyProfile = DEMO_COMPANY_PROFILES[scenario]
  state.dataProfile = DEMO_DATA_PROFILES[scenario]
  state.architectureProfile = DEMO_ARCHITECTURE_PROFILES[scenario]
  state.currentStep = 'security-profile'

  state.steps = state.steps.map((step, index) => ({
    ...step,
    completed: index < 3,
    validatedAt: index < 3 ? now : null,
  }))

  return state
}

// =============================================================================
// EXPORTS
// =============================================================================

export {
  DEMO_COMPANY_PROFILES as demoCompanyProfiles,
  DEMO_DATA_PROFILES as demoDataProfiles,
  DEMO_ARCHITECTURE_PROFILES as demoArchitectureProfiles,
  DEMO_SECURITY_PROFILES as demoSecurityProfiles,
  DEMO_RISK_PROFILES as demoRiskProfiles,
  DEMO_EVIDENCE_DOCUMENTS as demoEvidenceDocuments,
}
