/**
 * DSR Types — API Types, Communication, Audit, Templates, Statistics & Helpers
 */

import type {
  DSRType,
  DSRStatus,
  DSRPriority,
  DSRSource,
  DSRRequester,
  DSRAssignment,
  DSRRequest,
  DSRDataExport,
  IdentityVerificationMethod,
  CommunicationType,
  CommunicationChannel,
  DSRTypeInfo,
} from './types-core'

export { DSR_TYPE_INFO } from './types-core'

// =============================================================================
// COMMUNICATION
// =============================================================================

export interface DSRCommunication {
  id: string
  dsrId: string
  type: CommunicationType
  channel: CommunicationChannel
  subject?: string
  content: string
  templateUsed?: string
  attachments?: {
    name: string
    url: string
    size: number
    type: string
  }[]
  sentAt?: string
  sentBy?: string
  receivedAt?: string
  createdAt: string
  createdBy: string
}

// =============================================================================
// AUDIT LOG
// =============================================================================

export interface DSRAuditEntry {
  id: string
  dsrId: string
  action: string
  previousValue?: string
  newValue?: string
  performedBy: string
  performedAt: string
  notes?: string
}

// =============================================================================
// EMAIL TEMPLATES
// =============================================================================

export interface DSREmailTemplate {
  id: string
  name: string
  subject: string
  body: string
  type: DSRType | 'general'
  stage: DSRStatus | 'identity_request' | 'deadline_extension' | 'completion'
  language: 'de' | 'en'
  variables: string[]
}

export const DSR_EMAIL_TEMPLATES: DSREmailTemplate[] = [
  {
    id: 'intake_confirmation',
    name: 'Eingangsbestaetigung',
    subject: 'Bestaetigung Ihrer Anfrage - {{referenceNumber}}',
    body: `Sehr geehrte(r) {{requesterName}},

wir bestaetigen den Eingang Ihrer Anfrage vom {{receivedDate}}.

Referenznummer: {{referenceNumber}}
Art der Anfrage: {{requestType}}

Wir werden Ihre Anfrage innerhalb der gesetzlichen Frist von {{deadline}} bearbeiten.

Mit freundlichen Gruessen
{{senderName}}
Datenschutzbeauftragter`,
    type: 'general',
    stage: 'intake',
    language: 'de',
    variables: ['requesterName', 'receivedDate', 'referenceNumber', 'requestType', 'deadline', 'senderName']
  },
  {
    id: 'identity_request',
    name: 'Identitaetsanfrage',
    subject: 'Identitaetspruefung erforderlich - {{referenceNumber}}',
    body: `Sehr geehrte(r) {{requesterName}},

um Ihre Anfrage bearbeiten zu koennen, benoetigen wir einen Nachweis Ihrer Identitaet.

Bitte senden Sie uns eines der folgenden Dokumente:
- Kopie Ihres Personalausweises (Vorder- und Rueckseite)
- Kopie Ihres Reisepasses

Ihre Daten werden ausschliesslich zur Identitaetspruefung verwendet und anschliessend geloescht.

Mit freundlichen Gruessen
{{senderName}}
Datenschutzbeauftragter`,
    type: 'general',
    stage: 'identity_request',
    language: 'de',
    variables: ['requesterName', 'referenceNumber', 'senderName']
  }
]

// =============================================================================
// API TYPES
// =============================================================================

export interface DSRFilters {
  status?: DSRStatus | DSRStatus[]
  type?: DSRType | DSRType[]
  priority?: DSRPriority
  assignedTo?: string
  overdue?: boolean
  search?: string
  dateFrom?: string
  dateTo?: string
}

export interface DSRListResponse {
  requests: DSRRequest[]
  total: number
  page: number
  pageSize: number
}

export interface DSRCreateRequest {
  type: DSRType
  requester: DSRRequester
  source: DSRSource
  sourceDetails?: string
  requestText?: string
  priority?: DSRPriority
}

export interface DSRUpdateRequest {
  status?: DSRStatus
  priority?: DSRPriority
  notes?: string
  internalNotes?: string
  assignment?: DSRAssignment
}

export interface DSRVerifyIdentityRequest {
  method: IdentityVerificationMethod
  notes?: string
  documentRef?: string
}

export interface DSRCompleteRequest {
  completionNotes?: string
  dataExport?: DSRDataExport
}

export interface DSRRejectRequest {
  reason: string
  legalBasis?: string
}

export interface DSRExtendDeadlineRequest {
  extensionMonths: 1 | 2
  reason: string
}

export interface DSRSendCommunicationRequest {
  type: CommunicationType
  channel: CommunicationChannel
  subject?: string
  content: string
  templateId?: string
}

// =============================================================================
// STATISTICS
// =============================================================================

export interface DSRStatistics {
  total: number
  byStatus: Record<DSRStatus, number>
  byType: Record<DSRType, number>
  overdue: number
  dueThisWeek: number
  averageProcessingDays: number
  completedThisMonth: number
}

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

export function getDaysRemaining(deadline: string): number {
  const deadlineDate = new Date(deadline)
  const now = new Date()
  const diff = deadlineDate.getTime() - now.getTime()
  return Math.ceil(diff / (1000 * 60 * 60 * 24))
}

export function isOverdue(request: DSRRequest): boolean {
  if (request.status === 'completed' || request.status === 'rejected' || request.status === 'cancelled') {
    return false
  }
  return getDaysRemaining(request.deadline.currentDeadline) < 0
}

export function isUrgent(request: DSRRequest, thresholdDays: number = 7): boolean {
  if (request.status === 'completed' || request.status === 'rejected' || request.status === 'cancelled') {
    return false
  }
  const daysRemaining = getDaysRemaining(request.deadline.currentDeadline)
  return daysRemaining >= 0 && daysRemaining <= thresholdDays
}

export function generateReferenceNumber(year: number, sequence: number): string {
  return `DSR-${year}-${String(sequence).padStart(6, '0')}`
}

export function getTypeInfo(type: DSRType): DSRTypeInfo {
  const { DSR_TYPE_INFO } = require('./types-core')
  return DSR_TYPE_INFO[type]
}

export function getStatusInfo(status: DSRStatus) {
  const { DSR_STATUS_INFO } = require('./types-core')
  return DSR_STATUS_INFO[status]
}
