// =============================================================================
// HELPER FUNCTIONS & INITIAL STATE FACTORY
// =============================================================================

import type { TOMGeneratorStepId, DataCategory, DataSubject, ProtectionLevel } from './enums'
import type { CIAAssessment, DataProfile, RiskProfile } from './profiles'
import type { TOMGeneratorState } from './state'
import type { StepConfig } from './step-config'
import { TOM_GENERATOR_STEPS } from './step-config'
import { DATA_CATEGORIES_METADATA } from './data-metadata'
import { DATA_SUBJECTS_METADATA } from './data-metadata'

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
