import axios from 'axios';
import { apiClient } from './api';
import type {
  Image,
  CreateImageRequest,
  UpdateOCRRequest,
} from '@/types';

const API_BASE_URL = import.meta.env.VITE_API_URL || '/api';

class ImageServiceClass {
  /**
   * Upload image file using FormData
   */
  async uploadFile(file: File, documentId?: string): Promise<Image> {
    try {
      const formData = new FormData();
      formData.append('file', file);
      if (documentId) {
        formData.append('document_id', documentId);
      }

      const token = localStorage.getItem('auth_token');
      const response = await axios.post<{ success: boolean; data: Image }>(
        `${API_BASE_URL}/images`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
            ...(token ? { Authorization: `Bearer ${token}` } : {}),
          },
        }
      );

      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 create(data: CreateImageRequest): Promise<Image> {
    try {
      const response = await apiClient.post<{ success: boolean; data: Image }>('/images', 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 getUserImages(documentId?: string): Promise<Image[]> {
    const url = documentId ? `/images?document_id=${documentId}` : '/images';
    const response = await apiClient.get<{ success: boolean; data: Image[] }>(url);
    return response.data.data || [];
  }

  async getPendingImages(): Promise<Image[]> {
    const response = await apiClient.get<{ success: boolean; data: Image[] }>('/images/pending');
    return response.data.data || [];
  }

  async getById(id: string): Promise<Image> {
    try {
      const response = await apiClient.get<{ success: boolean; data: Image }>(`/images/${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 updateOCR(id: string, data: UpdateOCRRequest): Promise<Image> {
    try {
      const response = await apiClient.put<{ success: boolean; data: Image }>(`/images/${id}/ocr`, 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 || '更新OCR结果失败');
    }
  }

  async linkToDocument(id: string, documentId: string): Promise<Image> {
    try {
      const response = await apiClient.put<{ success: boolean; data: Image }>(`/images/${id}/link`, { document_id: documentId });
      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(`/images/${id}`);
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '删除失败');
    }
  }

  /**
   * 重新处理图片 OCR
   * @param id 图片 ID
   * @param provider OCR 提供商 ('tesseract' | 'baidu' | 'rapidocr' | 'auto')
   */
  async reprocess(id: string, provider?: string): Promise<void> {
    try {
      await apiClient.post(`/images/${id}/reprocess`, { provider });
    } catch (error: any) {
      throw new Error(error.response?.data?.error || '重新处理失败');
    }
  }

  /**
   * 获取可用的 OCR 提供商列表
   */
  async getOCRProviders(): Promise<Array<{ type: string; name: string; available: boolean; typeDesc: string }>> {
    try {
      const response = await apiClient.get<{ success: boolean; data: Array<{ type: string; name: string; available: boolean; typeDesc: string }> }>('/images/ocr/providers');
      return response.data.data || [];
    } catch (error: any) {
      return [];
    }
  }
}

export const ImageService = new ImageServiceClass();
