export interface ChatSessionMeta {
  id: string
  title: string
  createdAt: number
  updatedAt: number
}

interface ChatSessionState {
  sessions: ChatSessionMeta[]
  activeSessionId: string
}

const STORAGE_PREFIX = 'chat-sessions:'

function storageKey(lobsterId: string): string {
  return `${STORAGE_PREFIX}${lobsterId}`
}

export function createChatSession(lobsterId: string, index: number): ChatSessionMeta {
  const timestamp = Date.now()
  const suffix = Math.random().toString(36).slice(2, 8)

  return {
    id: `lobster:${lobsterId}:${timestamp.toString(36)}-${suffix}`,
    title: `会话 ${index}`,
    createdAt: timestamp,
    updatedAt: timestamp,
  }
}

export function loadChatSessionState(lobsterId: string): ChatSessionState | null {
  try {
    const raw = localStorage.getItem(storageKey(lobsterId))
    if (!raw) return null

    const parsed = JSON.parse(raw) as unknown
    if (
      typeof parsed !== 'object' ||
      parsed === null ||
      !Array.isArray((parsed as ChatSessionState).sessions) ||
      typeof (parsed as ChatSessionState).activeSessionId !== 'string'
    ) {
      return null
    }

    const sessions = (parsed as ChatSessionState).sessions.filter(
      session =>
        typeof session?.id === 'string' &&
        typeof session?.title === 'string' &&
        typeof session?.createdAt === 'number' &&
        typeof session?.updatedAt === 'number',
    )

    if (sessions.length === 0) return null

    const activeSessionId = sessions.some(
      session => session.id === (parsed as ChatSessionState).activeSessionId,
    )
      ? (parsed as ChatSessionState).activeSessionId
      : sessions[0].id

    return {
      sessions,
      activeSessionId,
    }
  } catch {
    return null
  }
}

export function saveChatSessionState(
  lobsterId: string,
  state: ChatSessionState,
): void {
  try {
    localStorage.setItem(storageKey(lobsterId), JSON.stringify(state))
  } catch {
    // ignore
  }
}
