/**
 * HTTP API 客户端封装
 *
 * 与 socket.js 共用服务器配置
 * import { API_BASE } from './socket.js'
 */

import { API_BASE } from './socket.js';

/**
 * 封装 wx.request
 * @param {string} method - HTTP 方法
 * @param {string} path - API 路径（如 /rooms）
 * @param {object} [data] - 请求数据
 * @returns {Promise<any>}
 */
function request(method, path, data) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${API_BASE}${path}`,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          reject(new Error(`HTTP ${res.statusCode}: ${res.data?.error || 'Unknown error'}`));
        }
      },
      fail: reject,
    });
  });
}

// API 方法
export const api = {
  // 房间相关
  rooms: {
    // GET /api/rooms - 获取房间列表
    list: () => request('GET', '/rooms'),

    // POST /api/rooms - 创建房间
    create: (data) => request('POST', '/rooms', data),

    // GET /api/rooms/:id - 获取房间详情
    get: (id) => request('GET', `/rooms/${id}`),

    // GET /api/rooms/:id/check - 校验房间并返回队伍人数
    check: (id) => request('GET', `/rooms/${id}/check`),

    // PUT /api/rooms/:id - 更新房间
    update: (id, data) => request('PUT', `/rooms/${id}`, data),

    // DELETE /api/rooms/:id - 删除房间
    delete: (id) => request('DELETE', `/rooms/${id}`),

    // POST /api/rooms/:id/join - 加入房间
    join: (id, data) => request('POST', `/rooms/${id}/join`, data),

    // POST /api/rooms/:id/leave - 离开房间
    leave: (id, data) => request('POST', `/rooms/${id}/leave`, data),
  },

  // 会话相关
  sessions: {
    // GET /api/sessions - 获取会话列表
    list: () => request('GET', '/sessions'),

    // POST /api/sessions - 创建会话
    create: (data) => request('POST', '/sessions', data),

    // GET /api/sessions/:id - 获取会话详情
    get: (id) => request('GET', `/sessions/${id}`),
  },

  // 大屏相关
  screens: {
    // GET /api/screens - 获取大屏列表
    list: () => request('GET', '/screens'),

    // POST /api/screens - 创建大屏
    create: (data) => request('POST', '/screens', data),

    // GET /api/screens/:name - 获取大屏详情
    get: (name) => request('GET', `/screens/${name}`),
  },

  // 统计相关
  stats: {
    // GET /api/stats - 获取统计数据
    get: (params) => request('GET', '/stats', params),
  },
};

export default api;
