import { ApiDocument, ApiDocumentList, DocumentUploadResponse, DocumentDeleteResponse, DocumentProcessRequest, DocumentImportRequest } from './types';
import { apiClient } from './apiClient';

const DOCUMENTS_BASE = '/documents';

/**
 * Service for DOCX/PDF document management.
 * Handles upload, processing, AI enhancement, and import to memos.
 */
export const docxService = {
  /**
   * Upload a document file (DOCX, PDF, TXT)
   */
  async uploadDocument(
    file: File,
    workspaceId?: string,
    title?: string
  ): Promise<DocumentUploadResponse> {
    const formData = new FormData();
    formData.append('file', file);
    if (workspaceId) formData.append('workspace_id', workspaceId);
    if (title) formData.append('title', title);

    const response = await apiClient.post(`${DOCUMENTS_BASE}/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    return response.data as DocumentUploadResponse;
  },

  /**
   * List documents with optional filters
   */
  async listDocuments(
    params?: {
      workspace_id?: string;
      status?: string;
      limit?: number;
      offset?: number;
    }
  ): Promise<ApiDocumentList> {
    const searchParams = new URLSearchParams();
    if (params?.workspace_id) searchParams.append('workspace_id', params.workspace_id);
    if (params?.status) searchParams.append('status', params.status);
    if (params?.limit) searchParams.append('limit', params.limit.toString());
    if (params?.offset) searchParams.append('offset', params.offset.toString());

    const queryString = searchParams.toString();
    const url = queryString ? `${DOCUMENTS_BASE}?${queryString}` : DOCUMENTS_BASE;

    const response = await apiClient.get(url);
    return response.data as ApiDocumentList;
  },

  /**
   * Get a single document by ID
   */
  async getDocument(docId: number): Promise<ApiDocument> {
    const response = await apiClient.get(`${DOCUMENTS_BASE}/${docId}`);
    return response.data as ApiDocument;
  },

  /**
   * Update document metadata (title, tags, summary, workspace)
   */
  async updateDocument(
    docId: number,
    updates: Partial<Pick<ApiDocument, 'title' | 'tags' | 'summary' | 'workspace_id'>>
  ): Promise<ApiDocument> {
    const response = await apiClient.patch(`${DOCUMENTS_BASE}/${docId}`, updates);
    return response.data as ApiDocument;
  },

  /**
   * Manually trigger document processing and AI enhancement
   */
  async processDocument(
    docId: number,
    options?: DocumentProcessRequest
  ): Promise<ApiDocument> {
    const response = await apiClient.post(
      `${DOCUMENTS_BASE}/${docId}/process`,
      options || { enhance_with_ai: true, generate_summary: true, extract_tags: true }
    );
    return response.data as ApiDocument;
  },

  /**
   * Import document content as a new memo
   */
  async importDocument(
    docId: number,
    importOptions?: Partial<DocumentImportRequest>
  ): Promise<ApiDocument> {
    const response = await apiClient.post(
      `${DOCUMENTS_BASE}/${docId}/import`,
      importOptions || {}
    );
    return response.data as ApiDocument;
  },

  /**
   * Delete a document and its file
   */
  async deleteDocument(docId: number): Promise<DocumentDeleteResponse> {
    const response = await apiClient.delete(`${DOCUMENTS_BASE}/${docId}`);
    return response.data as DocumentDeleteResponse;
  },

  /**
   * Download the original document file
   */
  async downloadDocument(docId: number): Promise<Blob> {
    const response = await apiClient.get(`${DOCUMENTS_BASE}/${docId}/download`, {
      responseType: 'blob',
    });
    return response.data as Blob;
  },
};
