package com.haha.sdk.api;

import com.alibaba.fastjson2.JSON;
import com.haha.sdk.HahaClient;
import com.haha.sdk.exception.HahaException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * API基类
 * 提供通用的API调用方法
 * 
 * @author haha-sdk
 * @version 1.0.0
 */
@Slf4j
public abstract class BaseApi {
    
    protected final HahaClient client;
    
    protected BaseApi(HahaClient client) {
        this.client = client;
    }
    
    /**
     * POST请求
     * 注意：主动调用哈哈平台的API接口不需要签名
     * 签名机制仅用于回调通知接口的验证
     * 
     * @param path API路径
     * @param params 请求参数
     * @return 响应数据
     * @throws HahaException 调用失败时抛出
     */
    protected Map<String, Object> post(String path, Map<String, String> params) throws HahaException {
        try {
            String url = client.getConfig().getApiBaseUrl() + path;
            String response = client.getHttpUtils().post(url, params);
            Map<String, Object> result = client.getHttpUtils().parseResponse(response);
            
            // 检查返回码
            Integer code = (Integer) result.get("code");
            if (code == null || code != 1) {
                String msg = (String) result.get("info");
                throw new HahaException(code, "API调用失败: " + msg);
            }
            
            return result;
        } catch (Exception e) {
            if (e instanceof HahaException) {
                throw (HahaException) e;
            }
            throw new HahaException("API调用异常: " + e.getMessage(), e);
        }
    }
    
    /**
     * POST请求并解析返回的列表
     * 
     * @param path API路径
     * @param params 请求参数
     * @param clazz 列表元素类型
     * @param <T> 泛型类型
     * @param isList 是否为列表类型
     * @return 解析后的列表
     * @throws HahaException 调用失败时抛出
     */
    @SuppressWarnings("unchecked")
    protected <T> List<T> post(String path, Map<String, String> params, Class<T> clazz, boolean isList) throws HahaException {
        Map<String, Object> result = post(path, params);
        Object data = result.get("data");
        if (data == null) {
            return null;
        }
        
        // 将data转换为JSON字符串再解析为目标类型
        String json = JSON.toJSONString(data);
        return JSON.parseArray(json, clazz);
    }
}
