import { checkError, req } from "./req";
import { jwtDecode } from 'jwt-decode';

export interface IUser {
    id: string;
    username: string;
}

export interface IUserEx extends IUser {
    color?: string
}

export interface ICurrentUser extends IUser {
    token: string;
}

async function login(username: string, password: string): Promise<IUser> {
    const response = await req.post('login', { username, password });
    const json = await response.json();

    checkError(response, json);
    setLocalUser(json.token);

    return json;
}

async function signup(username: string, password: string) {
    const response = await req.post('signup', { username, password });
    const json = await response.json();

    checkError(response, json);
    setLocalUser(json.token);

    return json;
}

async function search(key: string) {
    const response = await req.get(`users/search/${key}`);
    const json = await response.json();

    checkError(response, json);

    return json.filter((u: IUser) => u.username !== currentUser()?.username);
}

function logOut() {
    setLocalUser(null);
}

function currentUser(): ICurrentUser | undefined {
    const token = sessionStorage.getItem('user-token');

    if (!token) {
        return;
    }

    const { username, id } = jwtDecode(token) as any;

    return { id, username: username, token };
}

export function setLocalUser(token: string | null) {
    if (token) {
        sessionStorage.setItem('user-token', token);
    } else {
        sessionStorage.removeItem('user-token');
    }
}

export const userReq = {
    signup,
    login,
    logOut,
    search,
    currentUser,
};