/**
 * Processing Activities — Helper Functions
 */

import type { ProcessingActivityFormData } from '../../types'
import type { ProcessingActivityTemplate, ProcessingActivityCategory } from './types'
import { HR_TEMPLATES, SALES_TEMPLATES } from './hr-sales'
import { MARKETING_TEMPLATES, FINANCE_TEMPLATES } from './marketing-finance'
import { IT_TEMPLATES, CUSTOMER_SERVICE_TEMPLATES, WEBSITE_TEMPLATES, GENERAL_TEMPLATES } from './it-customer-web-general'

export const PROCESSING_ACTIVITY_TEMPLATES: ProcessingActivityTemplate[] = [
  ...HR_TEMPLATES,
  ...SALES_TEMPLATES,
  ...MARKETING_TEMPLATES,
  ...FINANCE_TEMPLATES,
  ...IT_TEMPLATES,
  ...CUSTOMER_SERVICE_TEMPLATES,
  ...WEBSITE_TEMPLATES,
  ...GENERAL_TEMPLATES,
]

/**
 * Get templates by category
 */
export function getTemplatesByCategory(
  category: ProcessingActivityCategory
): ProcessingActivityTemplate[] {
  return PROCESSING_ACTIVITY_TEMPLATES.filter((t) => t.category === category)
}

/**
 * Get template by ID
 */
export function getTemplateById(id: string): ProcessingActivityTemplate | undefined {
  return PROCESSING_ACTIVITY_TEMPLATES.find((t) => t.id === id)
}

/**
 * Get all categories with their templates
 */
export function getGroupedTemplates(): Map<ProcessingActivityCategory, ProcessingActivityTemplate[]> {
  const grouped = new Map<ProcessingActivityCategory, ProcessingActivityTemplate[]>()

  for (const template of PROCESSING_ACTIVITY_TEMPLATES) {
    const existing = grouped.get(template.category) || []
    grouped.set(template.category, [...existing, template])
  }

  return grouped
}

/**
 * Create form data from template
 */
export function createFormDataFromTemplate(
  template: ProcessingActivityTemplate,
  organizationDefaults?: {
    responsible?: ProcessingActivityFormData['responsible']
    dpoContact?: ProcessingActivityFormData['dpoContact']
  }
): Partial<ProcessingActivityFormData> {
  return {
    vvtId: '',
    name: template.name,
    purposes: template.purposes,
    dataSubjectCategories: template.dataSubjectCategories,
    personalDataCategories: template.personalDataCategories,
    legalBasis: template.suggestedLegalBasis.map((type) => ({ type })),
    protectionLevel: template.suggestedProtectionLevel,
    dpiaRequired: template.dpiaLikely,
    retentionPeriod: {
      duration: template.suggestedRetentionYears,
      durationUnit: 'YEARS',
      description: { de: '', en: '' },
    },
    recipientCategories: [],
    thirdCountryTransfers: [],
    technicalMeasures: [],
    dataSources: [],
    systems: [],
    dataFlows: [],
    subProcessors: [],
    owner: '',
    responsible: organizationDefaults?.responsible,
    dpoContact: organizationDefaults?.dpoContact,
  }
}
