// 基础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,
  };

  // 添加认证token
  const token = localStorage.getItem('authToken');
  if (token) {
    defaultOptions.headers.Authorization = `Bearer ${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;
  }
};

// 基础实体类
class BaseEntity {
  constructor(endpoint) {
    this.endpoint = endpoint;
  }

  async list(orderBy = null) {
    let url = this.endpoint;
    if (orderBy) {
      url += `?order_by=${orderBy}`;
    }
    return await apiRequest(url);
  }

  async get(id) {
    return await apiRequest(`${this.endpoint}/${id}`);
  }

  async create(data) {
    return await apiRequest(this.endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async update(id, data) {
    return await apiRequest(`${this.endpoint}/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  }

  async delete(id) {
    return await apiRequest(`${this.endpoint}/${id}`, {
      method: 'DELETE',
    });
  }
}

// 材料实体类
export class Material extends BaseEntity {
  constructor() {
    super('/api/materials');
  }

  async upload(file) {
    const formData = new FormData();
    formData.append('file', file);
    
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
    const url = `${baseURL}/api/materials/upload`;
    
    const token = localStorage.getItem('authToken');
    const headers = {};
    if (token) {
      headers.Authorization = `Bearer ${token}`;
    }

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

    if (!response.ok) {
      throw new Error(`Upload failed: ${response.status}`);
    }

    return await response.json();
  }
}

// 热门话题实体类
export class HotTopic extends BaseEntity {
  constructor() {
    super('/api/hot-topics');
  }

  async getByPlatform(platform) {
    return await apiRequest(`${this.endpoint}?platform=${platform}`);
  }

  async getTrending() {
    return await apiRequest(`${this.endpoint}/trending`);
  }
}

// 花字模板实体类
export class FlowerTextTemplate extends BaseEntity {
  constructor() {
    super('/api/flower-text-templates');
  }

  async getByStyle(style) {
    return await apiRequest(`${this.endpoint}?style=${style}`);
  }
}

// 生图模板实体类
export class GenerationTemplate extends BaseEntity {
  constructor() {
    super('/api/generation-templates');
  }

  async getByStyle(style) {
    return await apiRequest(`${this.endpoint}?style=${style}`);
  }

  async generate(templateId, params) {
    return await apiRequest(`${this.endpoint}/${templateId}/generate`, {
      method: 'POST',
      body: JSON.stringify(params),
    });
  }
}

// 文案模板实体类
export class TextTemplate extends BaseEntity {
  constructor() {
    super('/api/text-templates');
  }

  async getByCategory(category) {
    return await apiRequest(`${this.endpoint}?category=${category}`);
  }

  async getByPlatform(platform) {
    return await apiRequest(`${this.endpoint}?platform=${platform}`);
  }

  async generate(templateId, params) {
    return await apiRequest(`${this.endpoint}/${templateId}/generate`, {
      method: 'POST',
      body: JSON.stringify(params),
    });
  }
}

// 创建单例实例
export const material = new Material();
export const hotTopic = new HotTopic();
export const flowerTextTemplate = new FlowerTextTemplate();
export const generationTemplate = new GenerationTemplate();
export const textTemplate = new TextTemplate(); 