import { ACCESS_TOKEN_STORAGE_KEY } from '@/constants/auth';
import { localStorage } from '@/utils/storage';

/**
 * 从统一 API 响应体中解析 token（兼容 token / accessToken 及嵌套在 data 内外的写法）
 */
export function extractTokenFromApiBody(body: unknown): string | null {
    if (!body || typeof body !== 'object') {
        return null;
    }
    const b = body as Record<string, unknown>;
    const inner = b.data;
    if (inner && typeof inner === 'object') {
        const d = inner as Record<string, unknown>;
        const t1 = d.token ?? d.accessToken;
        if (typeof t1 === 'string' && t1.length > 0) {
            return t1;
        }
    }
    const t2 = b.token ?? b.accessToken;
    if (typeof t2 === 'string' && t2.length > 0) {
        return t2;
    }
    return null;
}

export function getAccessToken(): string {
    try {
        const v = localStorage.get(ACCESS_TOKEN_STORAGE_KEY);
        if (typeof v === 'string' && v.length > 0) {
            return v;
        }
    } catch {
        /* 未写入或非字符串时忽略 */
    }
    return '';
}

export function setAccessToken(token: string): void {
    if (!token) {
        return;
    }
    localStorage.set(ACCESS_TOKEN_STORAGE_KEY, token);
}

export function removeAccessToken(): void {
    localStorage.remove(ACCESS_TOKEN_STORAGE_KEY);
}
