import { error } from '../model/error.js';
import { parse } from '../model/jwt.js';

export const logout = async ({ console, config, fetch }) => {
    const token = config.profiles[config.active_profile]?.token?.access_token;
    if (!token) {
        const err = new Error('Failed to logout. User is not logged-in');
        throw err;
    }
    const jwt = parse(token);
    const logoutUrl = new URL(jwt.iss);
    logoutUrl.pathname = '/oauth2/logout';
    logoutUrl.searchParams.set('app_tid', jwt.app_tid);
    logoutUrl.searchParams.set('id_token_hint', token);
    console.debug(`Logout from authorization server: ${logoutUrl}`);
    const res = await fetch(logoutUrl);
    if (res.status !== 302) {
        throw error(
            `Failed to logout: ${res.status} ${res.statusText} ` +
            await res.text(),
            res.status
        );
    }
    console.debug('Successfully logged-out');
};
