/**
 * Academy (E-Learning / Compliance Academy) Types
 *
 * TypeScript definitions for the E-Learning Academy module
 * Provides course management, enrollment tracking, and certificate generation
 * for DSGVO, IT-Security, AI Literacy, and Whistleblower compliance training
 */

// =============================================================================
// ENUMS & CONSTANTS
// =============================================================================

export type CourseCategory =
  | 'dsgvo_basics'              // DSGVO-Grundlagen
  | 'it_security'               // IT-Sicherheit
  | 'ai_literacy'               // AI Literacy
  | 'whistleblower_protection'  // Hinweisgeberschutz
  | 'custom'                    // Benutzerdefiniert

export type EnrollmentStatus =
  | 'not_started'   // Nicht gestartet
  | 'in_progress'   // In Bearbeitung
  | 'completed'     // Abgeschlossen
  | 'expired'       // Abgelaufen

export type LessonType = 'video' | 'text' | 'quiz'

// =============================================================================
// COURSE CATEGORY METADATA
// =============================================================================

export interface CourseCategoryInfo {
  label: string
  description: string
  icon: string
  color: string
  bgColor: string
}

export const COURSE_CATEGORY_INFO: Record<CourseCategory, CourseCategoryInfo> = {
  dsgvo_basics: {
    label: 'DSGVO-Grundlagen',
    description: 'Grundlagenwissen zur Datenschutz-Grundverordnung fuer alle Mitarbeiter',
    icon: 'Shield',
    color: 'text-blue-700',
    bgColor: 'bg-blue-100'
  },
  it_security: {
    label: 'IT-Sicherheit',
    description: 'Cybersecurity Awareness und sichere IT-Nutzung im Arbeitsalltag',
    icon: 'Lock',
    color: 'text-red-700',
    bgColor: 'bg-red-100'
  },
  ai_literacy: {
    label: 'AI Literacy',
    description: 'Sicherer und verantwortungsvoller Umgang mit kuenstlicher Intelligenz',
    icon: 'Brain',
    color: 'text-purple-700',
    bgColor: 'bg-purple-100'
  },
  whistleblower_protection: {
    label: 'Hinweisgeberschutz',
    description: 'Hinweisgeberschutzgesetz (HinSchG) und interne Meldestellen',
    icon: 'Megaphone',
    color: 'text-orange-700',
    bgColor: 'bg-orange-100'
  },
  custom: {
    label: 'Benutzerdefiniert',
    description: 'Individuell erstellte Schulungsinhalte und unternehmensspezifische Kurse',
    icon: 'Pencil',
    color: 'text-gray-700',
    bgColor: 'bg-gray-100'
  }
}

// =============================================================================
// ENROLLMENT STATUS METADATA
// =============================================================================

export const ENROLLMENT_STATUS_INFO: Record<EnrollmentStatus, { label: string; color: string; bgColor: string; borderColor: string }> = {
  not_started: {
    label: 'Nicht gestartet',
    color: 'text-gray-700',
    bgColor: 'bg-gray-100',
    borderColor: 'border-gray-200'
  },
  in_progress: {
    label: 'In Bearbeitung',
    color: 'text-yellow-700',
    bgColor: 'bg-yellow-100',
    borderColor: 'border-yellow-200'
  },
  completed: {
    label: 'Abgeschlossen',
    color: 'text-green-700',
    bgColor: 'bg-green-100',
    borderColor: 'border-green-200'
  },
  expired: {
    label: 'Abgelaufen',
    color: 'text-red-700',
    bgColor: 'bg-red-100',
    borderColor: 'border-red-200'
  }
}

// =============================================================================
// MAIN INTERFACES
// =============================================================================

export interface Course {
  id: string
  title: string
  description: string
  category: CourseCategory
  lessons: Lesson[]
  durationMinutes: number
  passingScore: number
  isActive: boolean
  status: 'draft' | 'published'
  requiredForRoles: string[]
  createdAt: string
  updatedAt: string
}

export interface Lesson {
  id: string
  courseId: string
  title: string
  type: LessonType
  contentMarkdown: string
  videoUrl?: string
  order: number
  durationMinutes: number
  quizQuestions?: QuizQuestion[]
}

export interface QuizQuestion {
  id: string
  lessonId: string
  question: string
  options: string[]
  correctOptionIndex: number
  explanation: string
}

export interface Enrollment {
  id: string
  courseId: string
  userId: string
  userName: string
  userEmail: string
  status: EnrollmentStatus
  progress: number // 0-100
  startedAt: string
  completedAt?: string
  certificateId?: string
  deadline: string
}

export interface Certificate {
  id: string
  enrollmentId: string
  courseId: string
  userId: string
  userName: string
  courseName: string
  issuedAt: string
  validUntil: string
  pdfUrl: string
}

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

export interface AcademyStatistics {
  totalCourses: number
  totalEnrollments: number
  completionRate: number              // 0-100
  overdueCount: number
  byCategory: Record<CourseCategory, number>
  byStatus: Record<EnrollmentStatus, number>
}

// =============================================================================
// API TYPES (REQUEST / RESPONSE)
// =============================================================================

export interface CourseListResponse {
  courses: Course[]
  total: number
  page: number
  pageSize: number
}

export interface EnrollmentListResponse {
  enrollments: Enrollment[]
  total: number
  page: number
  pageSize: number
}

export interface CourseCreateRequest {
  title: string
  description: string
  category: CourseCategory
  durationMinutes: number
  passingScore?: number
  requiredForRoles?: string[]
}

export interface CourseUpdateRequest {
  title?: string
  description?: string
  category?: CourseCategory
  durationMinutes?: number
  passingScore?: number
  status?: 'draft' | 'published'
  requiredForRoles?: string[]
}

export interface GenerateCourseRequest {
  moduleId: string
  title?: string
  category?: CourseCategory
  description?: string
  regulationArea?: string
  language?: string
  durationMinutes?: number
}

export interface EnrollUserRequest {
  courseId: string
  userId: string
  userName: string
  userEmail: string
  deadline: string
}

export interface UpdateProgressRequest {
  progress: number
  lessonId?: string
}

export interface SubmitQuizRequest {
  answers: number[] // Index der ausgewaehlten Antwort pro Frage
}

export interface SubmitQuizResponse {
  score: number
  passed: boolean
  correctAnswers: number
  totalQuestions: number
  results: { questionId: string; correct: boolean; explanation: string }[]
}

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

/**
 * Berechnet die Abschlussrate fuer eine Liste von Einschreibungen in Prozent (0-100)
 */
export function getCompletionPercentage(enrollments: Enrollment[]): number {
  if (enrollments.length === 0) return 0
  const completed = enrollments.filter(e => e.status === 'completed').length
  return Math.round((completed / enrollments.length) * 100)
}

/**
 * Prueft ob eine Einschreibung ueberfaellig ist (Deadline ueberschritten und nicht abgeschlossen)
 */
export function isEnrollmentOverdue(enrollment: Enrollment): boolean {
  if (enrollment.status === 'completed' || enrollment.status === 'expired') {
    return false
  }
  const deadlineDate = new Date(enrollment.deadline)
  const now = new Date()
  return deadlineDate.getTime() < now.getTime()
}

/**
 * Berechnet die verbleibenden Tage bis zur Deadline
 * Negative Werte bedeuten ueberfaellig
 */
export function getDaysUntilDeadline(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 getCategoryInfo(category: CourseCategory): CourseCategoryInfo {
  return COURSE_CATEGORY_INFO[category]
}

export function getStatusInfo(status: EnrollmentStatus) {
  return ENROLLMENT_STATUS_INFO[status]
}
