import { api, withApiBase } from './http';

export interface ChatSession {
  id: string;
  agentId: string;
  title: string;
  archived?: boolean;
  createdAt: number;
  updatedAt: number;
  messageCount?: number;
  lastPreview?: string;
  lastAt?: number;
}

export interface SearchHit {
  id: string;
  sessionId: string;
  sessionTitle: string;
  sessionArchived: boolean;
  role: 'user' | 'assistant';
  content: string;
  snippet: string;
  createdAt: number;
}

export interface SearchResult {
  sessions: { id: string; title: string; archived: boolean; created_at: number; updated_at: number }[];
  messages: SearchHit[];
}

export const SessionAPI = {
  list: (agentId: string, archived: '0' | '1' | 'all' = '0') =>
    api.get<ChatSession[]>(`/agents/${agentId}/sessions`, { params: { archived } }).then((r) => r.data),
  create: (agentId: string, title?: string) => api.post<ChatSession>(`/agents/${agentId}/sessions`, { title }).then((r) => r.data),
  rename: (agentId: string, sessionId: string, title: string) => api.put(`/agents/${agentId}/sessions/${sessionId}`, { title }).then((r) => r.data),
  remove: (agentId: string, sessionId: string) => api.delete(`/agents/${agentId}/sessions/${sessionId}`).then((r) => r.data),
  archive: (agentId: string, sessionId: string, archived: boolean) =>
    api.post(`/agents/${agentId}/sessions/${sessionId}/archive`, { archived }).then((r) => r.data),
  share: (agentId: string, sessionId: string, ttlHours = 0) =>
    api.post<{ token: string; expiresAt?: number }>(`/agents/${agentId}/sessions/${sessionId}/share`, { ttlHours }).then((r) => r.data),
  revokeShare: (agentId: string, sessionId: string) => api.delete(`/agents/${agentId}/sessions/${sessionId}/share`).then((r) => r.data),
  search: (agentId: string, q: string, opts: { includeArchived?: boolean; limit?: number } = {}) =>
    api
      .get<SearchResult>(`/agents/${agentId}/sessions/search`, {
        params: {
          q,
          includeArchived: opts.includeArchived ? '1' : '0',
          limit: opts.limit ?? 30
        }
      })
      .then((r) => r.data),
  exportSession: (agentId: string, sessionId: string, format: 'md' | 'json' = 'md') => {
    const url = withApiBase(`/agents/${agentId}/sessions/${sessionId}/export?format=${format}`);
    const a = document.createElement('a');
    a.href = url;
    a.rel = 'noopener';
    document.body.appendChild(a);
    a.click();
    a.remove();
  }
};

export const SharedAPI = {
  get: (token: string) =>
    api
      .get<{
        agent: { name: string; description: string };
        session: { id: string; title: string; createdAt: number; updatedAt: number };
        messages: { id: string; role: 'user' | 'assistant'; content: string; createdAt: number }[];
      }>(`/shared/${token}`)
      .then((r) => r.data)
};

