import {UserProfile} from 'mattermost-redux/types/users';

export function getUserDisplayName(user: UserProfile): string {
    if (user.nickname) {
        return user.nickname;
    }
    if (user.first_name || user.last_name) {
        return `${user.first_name} ${user.last_name}`.trim();
    }
    return user.username;
}

export function debounce<T extends(...args: any[]) => void>(fn: T, delay: number): T {
    let timer: ReturnType<typeof setTimeout>;
    return ((...args: any[]) => {
        clearTimeout(timer);
        timer = setTimeout(() => fn(...args), delay);
    }) as unknown as T;
}

export function getServerErrorId(err: unknown): string {
    const msg = (err as {message?: string})?.message || '';
    try {
        const parsed = JSON.parse(msg);
        return parsed.id || '';
    } catch {
        return '';
    }
}
