import { ref, watch } from 'vue'
import { useCookie } from '#imports'

type SortCookie = {
  field?: string
  direction?: string
}

const readSortCookie = (value: unknown): SortCookie | null => {
  if (!value) {
    return null
  }
  if (typeof value === 'object') {
    return value as SortCookie
  }
  if (typeof value === 'string') {
    try {
      return JSON.parse(value) as SortCookie
    } catch {
      return null
    }
  }
  return null
}

export const usePersistedSort = <
  TField extends string,
  TDirection extends string,
>(
  key: string,
  defaults: { field: TField; direction: TDirection },
) => {
  const cookie = useCookie<string | null>(`sort:${key}`, {
    sameSite: 'lax',
  })
  const stored = readSortCookie(cookie.value)
  const sortField = ref<TField>((stored?.field as TField) || defaults.field)
  const sortDirection = ref<TDirection>(
    (stored?.direction as TDirection) || defaults.direction,
  )

  watch([sortField, sortDirection], () => {
    cookie.value = JSON.stringify({
      field: sortField.value,
      direction: sortDirection.value,
    })
  })

  return {
    sortField,
    sortDirection,
  }
}
