import Cookies from "js-cookie";
import config from "@/config";
import loginService from "@/api/auth/loginService";
import userService from "@/api/sys/userService";
import tenantService from "@/api/sys/tenantService";
import store from "@/store";
import tool from "@/utils/tool";
import {
	getKeycloakAccessToken,
	initializeKeycloak,
	isOidcEnabled,
	isOidcRequired,
} from "./keycloak";

function isOidcCallback() {
	const params = new URLSearchParams(window.location.search);
	return params.has("state") && (params.has("code") || params.has("error"));
}

export async function bootstrapOidcSession() {
	if (!isOidcEnabled) {
		return;
	}

	const callback = isOidcCallback();
	const localToken = tool.data.get(config.TOKEN);
	if (!isOidcRequired && !callback && localToken) {
		return;
	}

	const authenticated = await initializeKeycloak({
		loginRequired: isOidcRequired,
		checkSso: !isOidcRequired && !callback,
	});
	if (!authenticated) {
		if (!isOidcRequired) {
			return;
		}
		throw new Error("Keycloak authentication did not establish a session");
	}
	const accessToken = getKeycloakAccessToken();
	if (!accessToken) {
		throw new Error(
			"Keycloak authentication did not return an access token"
		);
	}

	const loginResponse = await loginService.oidcLogin(accessToken);
	tool.data.set(config.TOKEN, loginResponse.token);
	Cookies.set(config.TOKEN, loginResponse.token);
	tool.data.set("AUTH_SOURCE", "oidc");

	const { user } = await userService.info();
	tool.data.set("USER_INFO", user);
	store.commit("user/updateUser", user);

	const isPrimaryTenant = user.tenantDTO.id === "10000";
	tool.data.set("IS_PRIMARY_TENANT", isPrimaryTenant);
	if (isPrimaryTenant) {
		const tenants = await tenantService.list();
		tool.data.set("TENANT_LIST", tenants.records);
	} else {
		tool.data.remove("TENANT_LIST");
	}

	const { menuList, permissions, dictList } = await userService.getMenus();
	if (!menuList || menuList.length === 0) {
		throw new Error("当前用户在此系统没有任何菜单权限，请联系系统管理员");
	}
	tool.data.set("MENU", menuList);
	tool.data.set("PERMISSIONS", permissions);
	tool.data.set("DICT_LIST", dictList);
}
