// 素材库API接口
const apiRequest = async (endpoint, options = {}) => {
  const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
  const url = `${baseURL}${endpoint}`;
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
    },
    ...options,
  };

  // 注意：素材库API目前不需要认证
  // 如果需要认证，可以在这里添加token

  try {
    const response = await fetch(url, defaultOptions);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('API request failed:', error);
    throw error;
  }
};

// 素材库API类
export class MaterialLibraryAPI {
  constructor() {
    this.baseURL = '/api/v1';
  }

  // 上传素材
  async uploadMaterial(userId, file, imageType, originalFilename) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('image_type', imageType);
    formData.append('original_filename', originalFilename);
    
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
    const url = `${baseURL}${this.baseURL}/users/${userId}/materials`;
    
    console.log('上传请求详情:', {
      url,
      userId,
      imageType,
      originalFilename,
      fileSize: file.size,
      baseURL
    });
    
    const headers = {};
    // 注意：素材库API目前不需要认证
    // 如果需要认证，可以在这里添加token

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers,
        body: formData,
      });

      console.log('上传响应状态:', response.status, response.statusText);

      if (!response.ok) {
        const errorText = await response.text();
        console.error('上传失败详情:', errorText);
        throw new Error(`Upload failed: ${response.status} - ${errorText}`);
      }

      const result = await response.json();
      console.log('上传成功结果:', result);
      return result;
    } catch (error) {
      console.error('上传请求异常:', error);
      throw error;
    }
  }

  // 获取素材列表
  async getMaterials(userId, materialType = null, page = 1, pageSize = 20) {
    let url = `${this.baseURL}/users/${userId}/materials?page=${page}&page_size=${pageSize}`;
    if (materialType) {
      url += `&material_type=${materialType}`;
    }
    
    return await apiRequest(url);
  }

  // 删除素材
  async deleteMaterial(userId, materialId) {
    return await apiRequest(`${this.baseURL}/users/${userId}/materials/${materialId}`, {
      method: 'DELETE',
    });
  }

  // 更新素材信息
  async updateMaterial(userId, materialId, data) {
    return await apiRequest(`${this.baseURL}/users/${userId}/materials/${materialId}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  }
}

// 创建单例实例
export const materialLibraryAPI = new MaterialLibraryAPI(); 