import { ref } from 'vue'
import { http } from '@/api'

const LEGACY_HISTORY = 'nexus_servers_search_history'
const LEGACY_LAST = 'nexus_servers_search_last'

export interface ServerSearchHistoryResponse {
  history: string[]
  last: string | null
}

function readLegacyLocal(): { history: string[]; last: string } | null {
  try {
    const raw = localStorage.getItem(LEGACY_HISTORY)
    const last = localStorage.getItem(LEGACY_LAST) || ''
    if (!raw) return last.trim() ? { history: [], last } : null
    const parsed = JSON.parse(raw) as unknown
    if (!Array.isArray(parsed)) return last.trim() ? { history: [], last } : null
    const history = parsed.filter((x): x is string => typeof x === 'string' && x.trim().length > 0)
    if (!history.length && !last.trim()) return null
    return { history, last }
  } catch {
    return null
  }
}

function clearLegacyLocal() {
  try {
    localStorage.removeItem(LEGACY_HISTORY)
    localStorage.removeItem(LEGACY_LAST)
  } catch {
    // ignore
  }
}

/** Servers / push page search history — persisted per admin in MySQL. */
export type ServerSearchHistoryScope = 'servers' | 'push' | 'terminal'

const HISTORY_ENDPOINT: Record<ServerSearchHistoryScope, string> = {
  servers: '/servers/search-history',
  push: '/servers/push-search-history',
  terminal: '/servers/terminal-search-history',
}

/** Per-admin search history in MySQL (servers or push scope). */
export function useServerSearchHistory(scope: ServerSearchHistoryScope = 'servers') {
  const items = ref<string[]>([])
  const bootstrapped = ref(false)
  const endpoint = HISTORY_ENDPOINT[scope]

  async function load(): Promise<void> {
    const res = await http.get<ServerSearchHistoryResponse>(endpoint)
    items.value = res.history || []
  }

  async function migrateLegacyIfEmpty(): Promise<boolean> {
    if (scope !== 'servers') return false
    const legacy = readLegacyLocal()
    if (!legacy) return false
    if (items.value.length > 0) {
      clearLegacyLocal()
      return false
    }
    await http.put<ServerSearchHistoryResponse>(endpoint, {
      history: legacy.history,
      last: legacy.last || legacy.history[0] || '',
    })
    clearLegacyLocal()
    return true
  }

  /** Load dropdown history only — does not apply any search to the list. */
  async function loadHistoryOnly(): Promise<void> {
    if (bootstrapped.value) return
    try {
      await load()
      if (!items.value.length && (await migrateLegacyIfEmpty())) {
        await load()
      }
    } catch {
      // offline / auth — keep empty history
    } finally {
      bootstrapped.value = true
    }
  }

  async function record(query: string | null | undefined) {
    const normalized = String(query ?? '').trim()
    try {
      const res = await http.put<ServerSearchHistoryResponse>(endpoint, {
        query: normalized,
      })
      items.value = res.history || []
    } catch {
      // non-blocking
    }
  }

  return { items, bootstrapped, load, loadHistoryOnly, record }
}
