import { apiClient } from './api';
import type {
  Document,
  CreateDocumentRequest,
  UpdateDocumentRequest,
} from '@/types';

// AI 分析结果类型
export interface AIAnalysisResult {
  suggested_tags: string[];
  suggested_category?: string;
  summary?: string;
  raw_response: string;
  provider: string;
  model: string;
}

class DocumentServiceClass {
  async create(data: CreateDocumentRequest): Promise<Document> {
    try {
      const response = await apiClient.post<{ success: boolean; data: Document }>('/documents', data);
      if (response.data.success && response.data.data) {
        return response.data.data;
      }
      throw new Error('创建失败');
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '创建文档失败');
    }
  }

  async getUserDocuments(params?: { page?: number; limit?: number }): Promise<Document[]> {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append('page', params.page.toString());
    if (params?.limit) queryParams.append('limit', params.limit.toString());

    const url = `/documents${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
    const response = await apiClient.get<{ success: boolean; data: Document[] }>(url);
    return response.data.data || [];
  }

  async getById(id: string): Promise<Document> {
    try {
      const response = await apiClient.get<{ success: boolean; data: Document }>(`/documents/${id}`);
      if (response.data.success && response.data.data) {
        return response.data.data;
      }
      throw new Error('获取失败');
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '文档不存在');
    }
  }

  async update(id: string, data: UpdateDocumentRequest): Promise<Document> {
    try {
      const response = await apiClient.put<{ success: boolean; data: Document }>(`/documents/${id}`, data);
      if (response.data.success && response.data.data) {
        return response.data.data;
      }
      throw new Error('更新失败');
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '更新文档失败');
    }
  }

  async delete(id: string): Promise<void> {
    try {
      await apiClient.delete(`/documents/${id}`);
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '删除失败');
    }
  }

  async search(query: string): Promise<Document[]> {
    const response = await apiClient.get<{ success: boolean; data: Document[] }>(`/documents/search?q=${encodeURIComponent(query)}`);
    return response.data.data || [];
  }

  // AI 分析文档
  async analyzeDocument(id: string, options?: { provider?: string; generate_summary?: boolean }): Promise<AIAnalysisResult> {
    try {
      const response = await apiClient.post<{ success: boolean; data: AIAnalysisResult }>(
        `/documents/${id}/analyze`,
        options || {}
      );
      if (response.data.success && response.data.data) {
        return response.data.data;
      }
      throw new Error('AI 分析失败');
    } catch (error: any) {
      throw new Error(error.response?.data?.error || 'AI 分析失败');
    }
  }

  // 获取文档的 AI 分析结果
  async getAnalysis(id: string): Promise<AIAnalysisResult | null> {
    try {
      const response = await apiClient.get<{ success: boolean; data: AIAnalysisResult }>(
        `/documents/${id}/analysis`
      );
      if (response.data.success && response.data.data) {
        return response.data.data;
      }
      return null;
    } catch (error: any) {
      // 404 表示没有分析结果
      if (error.response?.status === 404) {
        return null;
      }
      throw new Error(error.response?.data?.error || '获取 AI 分析失败');
    }
  }

  // 删除文档的 AI 分析结果
  async deleteAnalysis(id: string): Promise<void> {
    try {
      await apiClient.delete(`/documents/${id}/analysis`);
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '删除 AI 分析失败');
    }
  }
}

export const DocumentService = new DocumentServiceClass();
