import { userLogin } from "../apis/services";

export type AuthCache = {
    uid: string;
    eid: string;
    privilege: string;
    token: string;
};

type LoginResponse = {
    result?: number;
    content?: string;
};

/**
 * 认证模块 - 处理用户登录和凭证信息
 */
const auth = {
    cache: null as AuthCache | null,

    /** 保存认证信息 */
    save(value: AuthCache): void {
        this.cache = value;
    },

    /** 获取缓存的认证信息 */
    load(): AuthCache | null {
        return this.cache;
    },

    /**
     * 用户登录
     * @param name 用户名
     */
    login: async function (name: string): Promise<AuthCache | null> {
        const normalizedName = typeof name === 'string' ? name.trim() : '';
        if (!normalizedName) {
            console.error('登录用户名不能为空');
            return null;
        }
        const loginReq = { content: { obj1: normalizedName } };
        try {
            const loginResp = await userLogin(loginReq) as LoginResponse;

            if (loginResp?.result === 1 && typeof loginResp.content === 'string') {
                const parsed = loginResp.content
                    .split(';')
                    .map((item) => item.split('=')[1]);

                const [, uid, eid, privilege, token] = parsed;
                if (uid && eid && privilege && token) {
                    const userData: AuthCache = { uid, eid, privilege, token };
                    this.save(userData);
                    return userData;
                }
            }
        } catch (error) {
            console.error(error);
        }

        return null;
    }
};

export default auth;
