import { ApiDocument, ApiDocumentList, DocumentUploadResponse, DocumentDeleteResponse, DocumentProcessRequest, DocumentImportRequest } from './types';
import { fetchJson } from './apiClient';
import { getAccessToken } from '@/auth-state';

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 fetchJson<DocumentUploadResponse>(`${DOCUMENTS_BASE}/upload`, {
      method: 'POST',
      body: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    return response;
  },

  /**
   * 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 fetchJson<ApiDocumentList>(url, { method: 'GET' });
    return response;
  },

  /**
   * Get a single document by ID
   */
  async getDocument(docId: number): Promise<ApiDocument> {
    const response = await fetchJson<ApiDocument>(`${DOCUMENTS_BASE}/${docId}`, { method: 'GET' });
    return response;
  },

  /**
   * 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 fetchJson<ApiDocument>(`${DOCUMENTS_BASE}/${docId}`, {
      method: 'PATCH',
      body: updates,
    });
    return response;
  },

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

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

  /**
   * Delete a document and its file
   */
  async deleteDocument(docId: number): Promise<DocumentDeleteResponse> {
    const response = await fetchJson<DocumentDeleteResponse>(`${DOCUMENTS_BASE}/${docId}`, {
      method: 'DELETE',
    });
    return response;
  },

  /**
   * Download the original document file
   */
  async downloadDocument(docId: number): Promise<Blob> {
    const token = getAccessToken();
    const headers = new Headers();
    if (token) {
      headers.set("Authorization", `Bearer ${token}`);
    }
    const response = await fetch(`${DOCUMENTS_BASE}/${docId}/download`, {
      headers,
    });
    if (!response.ok) {
      throw new Error(`Failed to download document: ${response.statusText}`);
    }
    return response.blob();
  },
};
