/**
 * Loeschfristen Baseline-Katalog — Helper Functions
 */

import type { LoeschfristPolicy } from '../loeschfristen-types'
import { createEmptyPolicy } from '../loeschfristen-types'
import type { BaselineTemplate } from './types'
import { FINANCE_LEGAL_TEMPLATES } from './finance-legal'
import { HR_TEMPLATES } from './hr'
import { IT_SECURITY_TEMPLATES } from './it-security'
import { MARKETING_CRM_TEMPLATES } from './marketing-crm'

export const BASELINE_TEMPLATES: BaselineTemplate[] = [
  ...HR_TEMPLATES,
  ...FINANCE_LEGAL_TEMPLATES,
  ...IT_SECURITY_TEMPLATES,
  ...MARKETING_CRM_TEMPLATES,
]

/**
 * Erstellt eine vollstaendige LoeschfristPolicy aus einem BaselineTemplate.
 */
export function templateToPolicy(template: BaselineTemplate): LoeschfristPolicy {
  const base = createEmptyPolicy()

  return {
    ...base,
    dataObjectName: template.dataObjectName,
    description: template.description,
    affectedGroups: [...template.affectedGroups],
    dataCategories: [...template.dataCategories],
    primaryPurpose: template.primaryPurpose,
    deletionTrigger: template.deletionTrigger,
    retentionDriver: template.retentionDriver,
    retentionDriverDetail: template.retentionDriverDetail,
    retentionDuration: template.retentionDuration,
    retentionUnit: template.retentionUnit,
    retentionDescription: template.retentionDescription,
    startEvent: template.startEvent,
    deletionMethod: template.deletionMethod,
    deletionMethodDetail: template.deletionMethodDetail,
    responsibleRole: template.responsibleRole,
    reviewInterval: template.reviewInterval,
    tags: [...template.tags],
  }
}

/**
 * Gibt alle Templates zurueck, die einen bestimmten Tag enthalten.
 */
export function getTemplatesByTag(tag: string): BaselineTemplate[] {
  return BASELINE_TEMPLATES.filter(t => t.tags.includes(tag))
}

/**
 * Findet ein Template anhand seiner templateId.
 */
export function getTemplateById(templateId: string): BaselineTemplate | undefined {
  return BASELINE_TEMPLATES.find(t => t.templateId === templateId)
}

/**
 * Gibt alle im Katalog verwendeten Tags als sortierte Liste zurueck.
 */
export function getAllTemplateTags(): string[] {
  const tags = new Set<string>()
  BASELINE_TEMPLATES.forEach(t => t.tags.forEach(tag => tags.add(tag)))
  return Array.from(tags).sort()
}
