import type { SchoolYearRecord } from '../api/schoolYears'

export const SELECTED_SCHOOL_YEAR_NAME_STORAGE_KEY = 'alrahma_selected_school_year_name'
export const SELECTED_SCHOOL_YEAR_STATUS_STORAGE_KEY = 'alrahma_selected_school_year_status'

function safeLocalStorage(): Storage | null {
  try {
    return typeof window !== 'undefined' ? window.localStorage : null
  } catch {
    return null
  }
}

export function isCurrentSchoolYear(year: Pick<SchoolYearRecord, 'is_current'> & { isCurrent?: boolean }): boolean {
  return Boolean(year.is_current || year.isCurrent)
}

export function isReadOnlySchoolYearStatus(status: string | null | undefined): boolean {
  const normalized = String(status ?? '').trim().toLowerCase()
  return normalized === 'closed' || normalized === 'archived'
}

export function isReadOnlySchoolYear(year: SchoolYearRecord | null | undefined): boolean {
  return year ? isReadOnlySchoolYearStatus(year.status) : false
}

export function getStoredSelectedSchoolYearName(): string | null {
  const storage = safeLocalStorage()
  const value = storage?.getItem(SELECTED_SCHOOL_YEAR_NAME_STORAGE_KEY)?.trim() ?? ''
  return value || null
}

export function getStoredSelectedSchoolYearStatus(): string | null {
  const storage = safeLocalStorage()
  const value = storage?.getItem(SELECTED_SCHOOL_YEAR_STATUS_STORAGE_KEY)?.trim() ?? ''
  return value || null
}

export function storeSelectedSchoolYear(year: SchoolYearRecord | null): void {
  const storage = safeLocalStorage()
  if (!storage) return

  if (!year) {
    storage.removeItem(SELECTED_SCHOOL_YEAR_NAME_STORAGE_KEY)
    storage.removeItem(SELECTED_SCHOOL_YEAR_STATUS_STORAGE_KEY)
    return
  }

  storage.setItem(SELECTED_SCHOOL_YEAR_NAME_STORAGE_KEY, year.name)
  storage.setItem(SELECTED_SCHOOL_YEAR_STATUS_STORAGE_KEY, year.status)
}

export function clearSelectedSchoolYear(): void {
  storeSelectedSchoolYear(null)
}

export function selectedSchoolYearHeaders(): Record<string, string> {
  const name = getStoredSelectedSchoolYearName()
  const status = getStoredSelectedSchoolYearStatus()
  const headers: Record<string, string> = {}

  if (name) {
    headers['X-School-Year'] = name
  }

  if (status) {
    headers['X-School-Year-Status'] = status
  }

  return headers
}

export function buildSchoolYearQuery(params: {
  schoolYearName?: string | null
  existing?: string | URLSearchParams
}): string {
  const query = new URLSearchParams(params.existing)

  const name = params.schoolYearName?.trim()
  if (name) {
    query.set('school_year', name)
  }

  const value = query.toString()
  return value ? `?${value}` : ''
}

export function withSelectedSchoolYearUrl(url: string): string {
  const name = getStoredSelectedSchoolYearName()
  if (!name) return url

  const [base, hash = ''] = url.split('#', 2)
  const [path, rawQuery = ''] = base.split('?', 2)
  const query = new URLSearchParams(rawQuery)
  query.delete('school_year_id')
  query.delete('year')
  query.set('school_year', name)

  const next = `${path}?${query.toString()}`
  return hash ? `${next}#${hash}` : next
}
