import { authentication, AuthenticationSession, commands } from 'vscode';
import Logger from '../common/logger';

export interface CodingAuthenticationSession extends AuthenticationSession {
	team: string;
	accessToken: string;
	refreshToken?: string;
	expiresIn?: Date;
	identityId?: number;
	email: string;
}

const defaultScopes = ['project', 'project:depot', 'user', 'user:email'];

export async function getSessions(createIfNone = true): Promise<CodingAuthenticationSession[] | undefined> {
	try {
		const sessionRes = await commands.executeCommand<CodingAuthenticationSession[]>(
			'codng.command.authentication',
			defaultScopes,
			createIfNone
		);
		return sessionRes;
	} catch (error) {
		console.log('>>> sessionRes', error);
		return;
	}
}

export async function getSession(
	{ timeout, silent } = { timeout: 10000, silent: true },
): Promise<CodingAuthenticationSession> {
	let timer: NodeJS.Timeout | undefined;
	const timeoutPromise = new Promise<void>(resolve => {
		timer = setTimeout(() => {
			Logger.appendLine('Timed out while waiting for repositories.', 'RepositoryFileSystemProvider');
			resolve();
		}, timeout);
	});

	const authPromise = authentication.getSession('coding', defaultScopes, {
		createIfNone: !silent,
		silent,
	});

	const res = (await Promise.race([authPromise, timeoutPromise])) as CodingAuthenticationSession;
	if (timer) {
		clearTimeout(timer);
	}
	return res;
}
