/**
 * Pure helpers for assignment mutation logic (overlap checks, span expansion).
 * Used by planning-client.tsx — extracted here to keep the client component leaner.
 */

import type { Assignment } from '@/lib/planning-types'
import { formatDateKey } from '@/lib/planning-config'

/**
 * Find all assignments that form a consecutive span with the given anchor.
 * Looks at same consultant + type + project, sorted by date.
 */
export function findConsecutiveSpan(assignments: Assignment[], anchor: Assignment): Assignment[] {
  const peers = assignments
    .filter((a) =>
      a.consultant_id === anchor.consultant_id &&
      a.appointment_type_id === anchor.appointment_type_id &&
      a.project_id === anchor.project_id,
    )
    .sort((a, b) => a.date.localeCompare(b.date))

  const idx = peers.findIndex((a) => a.id === anchor.id)
  if (idx === -1) return [anchor]

  let start = idx
  let end   = idx
  while (start > 0) {
    const diffMs = new Date(peers[start].date + 'T00:00:00').getTime() -
                   new Date(peers[start - 1].date + 'T00:00:00').getTime()
    if (Math.round(diffMs / 86400000) === 1) { start -= 1 } else { break }
  }
  while (end < peers.length - 1) {
    const diffMs = new Date(peers[end + 1].date + 'T00:00:00').getTime() -
                   new Date(peers[end].date + 'T00:00:00').getTime()
    if (Math.round(diffMs / 86400000) === 1) { end += 1 } else { break }
  }
  return peers.slice(start, end + 1)
}

/**
 * True if any existing assignment (not in the excluded set) occupies the
 * given dates for the consultant.
 */
export function hasOverlapOnDates(
  assignments: Assignment[],
  consultantId: string,
  dates: string[],
  excludeIds: Set<string>,
): boolean {
  const dateSet = new Set(dates)
  return assignments.some(
    (a) => a.consultant_id === consultantId && !excludeIds.has(a.id) && dateSet.has(a.date),
  )
}

/**
 * All calendar days (as 'YYYY-MM-DD' strings) between start and end, inclusive.
 */
export function datesInRange(start: string, end: string): string[] {
  const result: string[] = []
  const cur  = new Date(start + 'T00:00:00')
  const last = new Date(end   + 'T00:00:00')
  while (cur <= last) {
    result.push(formatDateKey(cur))
    cur.setDate(cur.getDate() + 1)
  }
  return result
}
