// Pure helpers extracted from `project-edit-form.tsx` (R-05).
// Kept as a sibling file rather than a cross-cutting lib/ module because they
// are tightly coupled to the edit form's semantics (KW handling, consultant
// labeling). See __tests__/project-edit-form-helpers.test.ts for the
// characterization net.

export interface ConsultantLike {
  display_name?: string | null
  first_name?: string | null
  last_name?: string | null
}

export function consultantLabel(c: ConsultantLike): string {
  if (c.display_name) return c.display_name
  const parts = [c.last_name, c.first_name].filter(Boolean)
  return parts.join(', ')
}

export function kwToDateRange(
  kw: number,
  year: number,
): { start: string; end: string } | null {
  if (kw < 1 || kw > 53 || year < 2000) return null
  const jan4 = new Date(Date.UTC(year, 0, 4))
  const dayOfWeek = jan4.getUTCDay() || 7
  const week1Monday = new Date(jan4)
  week1Monday.setUTCDate(jan4.getUTCDate() - (dayOfWeek - 1))
  const monday = new Date(week1Monday)
  monday.setUTCDate(week1Monday.getUTCDate() + (kw - 1) * 7)
  const friday = new Date(monday)
  friday.setUTCDate(monday.getUTCDate() + 4)
  const fmt = (d: Date) => {
    const m = String(d.getUTCMonth() + 1).padStart(2, '0')
    const day = String(d.getUTCDate()).padStart(2, '0')
    return `${d.getUTCFullYear()}-${m}-${day}`
  }
  return { start: fmt(monday), end: fmt(friday) }
}

export function getWeekdaysInRange(start: string, end: string): string[] {
  if (!start || !end || start > end) return []
  const dates: string[] = []
  const cur = new Date(start + 'T00:00:00')
  const last = new Date(end + 'T00:00:00')
  while (cur <= last) {
    const d = cur.getDay()
    if (d !== 0 && d !== 6) {
      const y = cur.getFullYear()
      const m = String(cur.getMonth() + 1).padStart(2, '0')
      const day = String(cur.getDate()).padStart(2, '0')
      dates.push(`${y}-${m}-${day}`)
    }
    cur.setDate(cur.getDate() + 1)
  }
  return dates
}

export function fmtDate(d: string): string {
  return new Date(d + 'T00:00:00').toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  })
}
