// =============================================================================
// TYPES
// =============================================================================

export interface AssignmentOverview {
  id: string
  dsb_user_id: string
  tenant_id: string
  tenant_name: string
  tenant_slug: string
  status: string
  contract_start: string
  contract_end: string | null
  monthly_hours_budget: number
  notes: string
  compliance_score: number
  hours_this_month: number
  hours_budget: number
  open_task_count: number
  urgent_task_count: number
  next_deadline: string | null
  created_at: string
  updated_at: string
}

export interface DSBDashboard {
  assignments: AssignmentOverview[]
  total_assignments: number
  active_assignments: number
  total_hours_this_month: number
  open_tasks: number
  urgent_tasks: number
  generated_at: string
}

export interface HourEntry {
  id: string
  assignment_id: string
  date: string
  hours: number
  category: string
  description: string
  billable: boolean
  created_at: string
}

export interface Task {
  id: string
  assignment_id: string
  title: string
  description: string
  category: string
  priority: string
  status: string
  due_date: string | null
  completed_at: string | null
  created_at: string
  updated_at: string
}

export interface Communication {
  id: string
  assignment_id: string
  direction: string
  channel: string
  subject: string
  content: string
  participants: string
  created_at: string
}

export interface HoursSummary {
  total_hours: number
  billable_hours: number
  by_category: Record<string, number>
  period: string
}

// =============================================================================
// CONSTANTS
// =============================================================================

export const DSB_USER_ID = '00000000-0000-0000-0000-000000000001'

export const TASK_CATEGORIES = [
  'DSFA-Pruefung', 'Betroffenenanfrage', 'Vorfall-Pruefung',
  'Audit-Vorbereitung', 'Richtlinien-Pruefung', 'Schulung',
  'Beratung', 'Sonstiges',
]

export const HOUR_CATEGORIES = [
  'DSFA-Pruefung', 'Beratung', 'Audit', 'Schulung',
  'Vorfallreaktion', 'Dokumentation', 'Besprechung', 'Sonstiges',
]

export const COMM_CHANNELS = ['E-Mail', 'Telefon', 'Besprechung', 'Portal', 'Brief']

export const PRIORITY_LABELS: Record<string, string> = {
  urgent: 'Dringend', high: 'Hoch', medium: 'Mittel', low: 'Niedrig',
}

export const PRIORITY_COLORS: Record<string, string> = {
  urgent: 'bg-red-100 text-red-700 border-red-200',
  high: 'bg-orange-100 text-orange-700 border-orange-200',
  medium: 'bg-blue-100 text-blue-700 border-blue-200',
  low: 'bg-gray-100 text-gray-500 border-gray-200',
}

export const TASK_STATUS_LABELS: Record<string, string> = {
  open: 'Offen', in_progress: 'In Bearbeitung', waiting: 'Wartend',
  completed: 'Erledigt', cancelled: 'Abgebrochen',
}

export const TASK_STATUS_COLORS: Record<string, string> = {
  open: 'bg-blue-100 text-blue-700',
  in_progress: 'bg-yellow-100 text-yellow-700',
  waiting: 'bg-orange-100 text-orange-700',
  completed: 'bg-green-100 text-green-700',
  cancelled: 'bg-gray-100 text-gray-500',
}

export const ASSIGNMENT_STATUS_COLORS: Record<string, string> = {
  active: 'bg-green-100 text-green-700 border-green-300',
  paused: 'bg-yellow-100 text-yellow-700 border-yellow-300',
  terminated: 'bg-red-100 text-red-700 border-red-300',
}

export const ASSIGNMENT_STATUS_LABELS: Record<string, string> = {
  active: 'Aktiv', paused: 'Pausiert', terminated: 'Beendet',
}

// =============================================================================
// API HELPERS
// =============================================================================

export async function apiFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      'X-User-ID': DSB_USER_ID,
      ...(options?.headers || {}),
    },
  })
  if (!res.ok) {
    const text = await res.text().catch(() => '')
    throw new Error(`API Error ${res.status}: ${text || res.statusText}`)
  }
  return res.json()
}

// =============================================================================
// DATE HELPERS
// =============================================================================

export function formatDate(dateStr: string | null): string {
  if (!dateStr) return '-'
  try {
    return new Date(dateStr).toLocaleDateString('de-DE', {
      day: '2-digit', month: '2-digit', year: 'numeric',
    })
  } catch { return dateStr }
}

export function formatDateTime(dateStr: string | null): string {
  if (!dateStr) return '-'
  try {
    return new Date(dateStr).toLocaleDateString('de-DE', {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit',
    })
  } catch { return dateStr }
}

export function currentMonth(): string {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`
}

export function monthLabel(ym: string): string {
  const [y, m] = ym.split('-')
  const months = [
    'Januar', 'Februar', 'Maerz', 'April', 'Mai', 'Juni',
    'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember',
  ]
  return `${months[parseInt(m, 10) - 1]} ${y}`
}

export function prevMonth(ym: string): string {
  const [y, m] = ym.split('-').map(Number)
  if (m === 1) return `${y - 1}-12`
  return `${y}-${String(m - 1).padStart(2, '0')}`
}

export function nextMonth(ym: string): string {
  const [y, m] = ym.split('-').map(Number)
  if (m === 12) return `${y + 1}-01`
  return `${y}-${String(m + 1).padStart(2, '0')}`
}
