// 会话持久化 API — 对接 Gateway REST API

import { request } from './client';
import type { Session, SessionListResponse, SessionMessagesResponse, SessionResponse } from '@/types/session';

/**
 * 获取用户的会话列表
 * GET /api/v1/sessions?user_id={userId}
 */
export async function fetchSessions(userId: string): Promise<Session[]> {
  const resp = await request<SessionListResponse>(
    `/sessions?user_id=${encodeURIComponent(userId)}`
  );
  if (resp.error) {
    console.error('[sessions] 获取会话列表失败:', resp.error);
    return [];
  }
  // Gateway 返回 { sessions: [...] }
  return (resp.data as SessionListResponse)?.sessions || [];
}

/**
 * 获取会话的消息历史
 * GET /api/v1/sessions/{sessionId}/messages?limit={limit}
 */
export async function fetchMessages(
  sessionId: string,
  limit: number = 50
): Promise<SessionMessagesResponse> {
  const resp = await request<SessionMessagesResponse>(
    `/sessions/${encodeURIComponent(sessionId)}/messages?limit=${limit}`
  );
  if (resp.error) {
    console.error('[sessions] 获取消息失败:', resp.error);
    return { messages: [] };
  }
  return (resp.data as SessionMessagesResponse) || { messages: [] };
}

/**
 * 创建新会话
 * POST /api/v1/sessions
 */
export async function createSession(
  userId: string,
  sessionId: string,
  title: string = '新的对话',
  isMain: boolean = false
): Promise<SessionResponse | null> {
  const resp = await request<SessionResponse>('/sessions', {
    method: 'POST',
    body: {
      user_id: userId,
      session_id: sessionId,
      title,
      is_main: isMain,
    },
  });
  if (resp.error) {
    console.error('[sessions] 创建会话失败:', resp.error);
    return null;
  }
  return resp.data as SessionResponse;
}

/**
 * 删除单个会话 (不删除记忆)
 * DELETE /api/v1/sessions/{sessionId}
 */
export async function deleteSession(sessionId: string): Promise<boolean> {
  const resp = await request(`/sessions/${encodeURIComponent(sessionId)}`, {
    method: 'DELETE',
  });
  if (resp.error) {
    console.error('[sessions] 删除会话失败:', resp.error);
    return false;
  }
  return true;
}

/**
 * 删除用户所有会话 (不删除记忆)
 * DELETE /api/v1/sessions?user_id={userId}
 */
export async function deleteAllSessions(userId: string): Promise<boolean> {
  const resp = await request(`/sessions?user_id=${encodeURIComponent(userId)}`, {
    method: 'DELETE',
  });
  if (resp.error) {
    console.error('[sessions] 删除所有会话失败:', resp.error);
    return false;
  }
  return true;
}

/**
 * 清空会话消息但不删除会话本身
 * DELETE /api/v1/sessions/{sessionId}/messages
 */
export async function clearSessionMessages(sessionId: string): Promise<boolean> {
  const resp = await request(
    `/sessions/${encodeURIComponent(sessionId)}/messages`,
    { method: 'DELETE' }
  );
  if (resp.error) {
    console.error('[sessions] 清空消息失败:', resp.error);
    return false;
  }
  return true;
}

// ========== 消息搜索 ==========

/** 单条搜索结果 */
export interface SearchResult {
  message_id: number;
  session_id: string;
  session_title: string;
  role: string;
  content: string;
  created_at: number; // UnixMilli
}

/** 搜索响应 */
export interface SearchResponse {
  results: SearchResult[];
  total: number;
  query: string;
  limit: number;
  offset: number;
}

/**
 * 全文搜索消息
 * GET /api/v1/messages/search?q={query}&user_id={userId}&limit={limit}&offset={offset}
 */
export async function searchMessages(
  query: string,
  userId: string,
  limit: number = 50,
  offset: number = 0
): Promise<SearchResponse> {
  const params = new URLSearchParams({
    q: query,
    user_id: userId,
    limit: String(limit),
    offset: String(offset),
  });
  const resp = await request<SearchResponse>(
    `/messages/search?${params.toString()}`
  );
  if (resp.error) {
    console.error('[sessions] 搜索消息失败:', resp.error);
    return { results: [], total: 0, query, limit, offset };
  }
  return (resp.data as SearchResponse) || { results: [], total: 0, query, limit, offset };
}

// ========== 导出 ==========

export type ExportFormat = 'json' | 'markdown' | 'txt';

/**
 * 导出会话为指定格式，触发浏览器下载
 * GET /api/v1/sessions/{sessionId}/export?format={format}
 */
export async function exportSession(
  sessionId: string,
  format: ExportFormat = 'json'
): Promise<void> {
  const token = localStorage.getItem('token');
  const resp = await fetch(
    `${import.meta.env.VITE_API_URL || '/api/v1'}/sessions/${encodeURIComponent(sessionId)}/export?format=${format}`,
    {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    }
  );

  if (!resp.ok) {
    const err = await resp.json().catch(() => ({ error: '导出失败' }));
    throw new Error(err.error || `导出失败 (${resp.status})`);
  }

  // 从 Content-Disposition 获取文件名，或生成默认名
  const disposition = resp.headers.get('Content-Disposition');
  let filename = `session_${sessionId}.${format}`;
  if (disposition) {
    const match = disposition.match(/filename="?([^";\n]+)"?/);
    if (match) filename = match[1];
  }

  // 触发浏览器下载
  const blob = await resp.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}
