// API基础URL
export const API_BASE_URL = 'http://localhost:8080'

// 获取认证令牌
const getAuthToken = () => {
  return localStorage.getItem('token')
}

// 通用请求方法
export const apiRequest = async (endpoint, options = {}) => {
  const token = getAuthToken()
  
  const config = {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    }
  }
  
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  
  try {
    const response = await fetch(`${API_BASE_URL}${endpoint}`, config)
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.message || `HTTP error! status: ${response.status}`)
    }
    
    // 检查响应是否为空
    const contentType = response.headers.get('content-type')
    if (contentType && contentType.includes('application/json')) {
      return await response.json()
    }
    
    return null
  } catch (error) {
    console.error('API Error:', error)
    throw error
  }
}

// 认证相关API
export const authAPI = {
  // 用户登录
  login: async (credentials) => {
    return apiRequest('/api/auth/login', {
      method: 'POST',
      body: JSON.stringify(credentials)
    })
  },
  
  // 用户注册
  register: async (userData) => {
    return apiRequest('/api/auth/register', {
      method: 'POST',
      body: JSON.stringify(userData)
    })
  },
  
  // 获取当前用户信息
  getCurrentUser: async () => {
    return apiRequest('/api/auth/me')
  }
}

// 歌单相关API
export const playlistAPI = {
  // 获取所有歌单
  getAll: async () => {
    return apiRequest('/api/playlists')
  },
  
  // 获取单个歌单
  getById: async (id) => {
    return apiRequest(`/api/playlists/${id}`)
  },
  
  // 创建歌单
  create: async (playlistData) => {
    return apiRequest('/api/playlists', {
      method: 'POST',
      body: JSON.stringify(playlistData)
    })
  },
  
  // 更新歌单
  update: async (id, playlistData) => {
    return apiRequest(`/api/playlists/${id}`, {
      method: 'PUT',
      body: JSON.stringify(playlistData)
    })
  },
  
  // 删除歌单
  delete: async (id) => {
    return apiRequest(`/api/playlists/${id}`, {
      method: 'DELETE'
    })
  },
  
  // 搜索歌单
  search: async (keyword) => {
    return apiRequest(`/api/playlists/search?keyword=${encodeURIComponent(keyword)}`)
  },
  
  // 复制歌单
  copy: async (id, newName) => {
    return apiRequest(`/api/playlists/${id}/copy?newName=${encodeURIComponent(newName)}`, {
      method: 'POST'
    })
  }
}

// 歌曲相关API
export const songAPI = {
  // 添加歌曲到歌单
  addToPlaylist: async (playlistId, songData) => {
    return apiRequest(`/api/playlists/${playlistId}/songs`, {
      method: 'POST',
      body: JSON.stringify(songData)
    })
  },
  
  // 从歌单移除歌曲
  removeFromPlaylist: async (playlistId, songId) => {
    return apiRequest(`/api/playlists/${playlistId}/songs/${songId}`, {
      method: 'DELETE'
    })
  }
}