/**
 * @file services.js
 * @description API服务模块 - 提供与后端交互的各种接口
 */

import { httpClient } from "./axios";
import configurator from "../components/conf";
import auth from "../components/auth";

type AssetFetchResult = {
    value: Uint8Array;
    timestamp: string;
};

/**
 * 获取资源数据的通用方法
 * @param {string} url - 资源基础URL
 * @param {string} obj - 资源路径
 * @returns {Promise<{value: Uint8Array, timestamp: string}|null>}
 */
const fetchAssetData = async (url: string, obj: string): Promise<AssetFetchResult | null> => {
    try {
        // 获取当前时间戳
        const currentTimestamp = Date.now().toString();
        const info = auth.load();
        if (!info) return null;
        // 将参数拼接到URL中
        const fullUrl = `${url}/${encodeURI(obj)}`;

        return await httpClient.get(fullUrl, {
            responseType: 'arraybuffer',
            headers: {
                Timestamp: currentTimestamp,
                Token: info.token ?? '',
                UUID: info.uid ?? ''
            }
        })
            .then(response => ({
                value: new Uint8Array(response.data as ArrayBuffer),
                timestamp: currentTimestamp,
            }))
            .catch(error => {
                console.error('Axios GET request error:', error);
                return null;
            });
    } catch (error) {
        console.error('Fetch asset data error:', error);
        return null;
    }
};

/**
 * 获取GLB模型数据
 * @param {string} obj - 模型文件路径
 * @returns {Promise<Uint8Array|null>} 模型二进制数据
 */
export const fetchGlbModel = async (obj: string): Promise<Uint8Array | null> => {
    const result = await fetchAssetData(configurator.modelAssetDir, obj);
    return result?.value ?? null;
};

/**
 * 用户登录
 * @param {object} obj - 登录请求参数
 * @param {object} obj.content - 登录内容
 * @param {string} obj.content.obj1 - 用户名
 * @returns {Promise<object>} 登录响应数据
 */
export const userLogin = async (obj: unknown): Promise<any> => {
    const data = await httpClient.post(`${httpClient.baseURL}/api/Terminal/ThreeJSToLogin`, obj);
    return data.data;
}

/**
 * 获取动画数据
 * @param {string} obj - 动画文件路径
 * @returns {Promise<object>} 动画数据
 */
export const fetchAnim = async (obj: string): Promise<any> => {
    const result = await httpClient.get(`${configurator.animAssetDir}/${obj}`);
    return result.data;
}
