/**
 * Zustand Store — 会话管理
 *
 * 会话列表、当前会话、搜索、置顶、归档。
 */

import { create } from 'zustand';

export interface Session {
  id: string;
  title: string;
  createdAt: number;
  updatedAt: number;
  messageCount: number;
  pinned: boolean;
  archived: boolean;
}

interface SessionState {
  sessions: Session[];
  currentSessionId: string | null;
  searchQuery: string;

  // Actions
  setSessions: (sessions: Session[]) => void;
  setCurrentSession: (id: string | null) => void;
  setSearchQuery: (query: string) => void;
  addSession: (session: Session) => void;
  updateSession: (id: string, updates: Partial<Session>) => void;
  removeSession: (id: string) => void;
  pinSession: (id: string, pinned: boolean) => void;
  archiveSession: (id: string, archived: boolean) => void;
}

export const useSessionStore = create<SessionState>((set) => ({
  // 初始状态
  sessions: [],
  currentSessionId: null,
  searchQuery: '',

  // Actions
  setSessions: (sessions) => set({ sessions }),
  setCurrentSession: (id) => set({ currentSessionId: id }),
  setSearchQuery: (query) => set({ searchQuery: query }),
  addSession: (session) =>
    set((s) => ({ sessions: [session, ...s.sessions] })),
  updateSession: (id, updates) =>
    set((s) => ({
      sessions: s.sessions.map((sess) =>
        sess.id === id ? { ...sess, ...updates } : sess,
      ),
    })),
  removeSession: (id) =>
    set((s) => ({
      sessions: s.sessions.filter((sess) => sess.id !== id),
      currentSessionId: s.currentSessionId === id ? null : s.currentSessionId,
    })),
  pinSession: (id, pinned) =>
    set((s) => ({
      sessions: s.sessions.map((sess) =>
        sess.id === id ? { ...sess, pinned } : sess,
      ),
    })),
  archiveSession: (id, archived) =>
    set((s) => ({
      sessions: s.sessions.map((sess) =>
        sess.id === id ? { ...sess, archived } : sess,
      ),
    })),
}));
