import { Component, inject } from '@angular/core';
import { getConfig, getKeycloakOptions, IStoredTenantId, KeycloakStatusService, TenantsService } from '@iqser/common-ui';
import { User } from '@red/domain';
import { KeycloakService } from 'keycloak-angular';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { BASE_HREF } from '@iqser/common-ui/lib/utils';

@Component({
    selector: 'app-tenants-menu',
    templateUrl: './tenants-menu.component.html',
    styleUrls: ['./tenants-menu.component.scss'],
})
export class TenantsMenuComponent {
    readonly #baseHref = inject(BASE_HREF);
    readonly #keycloakService = inject(KeycloakService);
    readonly #keycloakStatusService = inject(KeycloakStatusService);
    readonly #currentUser = getCurrentUser<User>();
    readonly #config = getConfig();
    readonly tenantsService = inject(TenantsService);
    readonly storedTenants: { key: string; value: IStoredTenantId[] }[];

    constructor() {
        this.storedTenants = this.#getStoredTenants();
    }

    trackBy(_index: number, item: { key: string; value: IStoredTenantId[] }) {
        return item.key;
    }

    // TODO: this should be moved to the keycloak status service
    async selectTenant(tenantId?: string, email?: string) {
        if (tenantId && tenantId !== this.tenantsService.activeTenantId) {
            await this.#keycloakService.init(getKeycloakOptions(this.#baseHref, this.#config, tenantId));
        }

        if (tenantId) {
            const url = this.#keycloakService.getKeycloakInstance().createLoginUrl({
                redirectUri: this.#keycloakStatusService.createLoginUrl(tenantId),
                idpHint: this.#config.OAUTH_IDP_HINT,
                loginHint: email ?? undefined,
            });
            return this.#keycloakService.logout(url);
        }

        return this.#keycloakService.logout(window.location.origin + this.#baseHref);
    }

    #getStoredTenants() {
        const storedTenants = this.tenantsService.getStoredTenants();

        const otherTenant = storedTenants.filter(t => {
            const isCurrentTenant = t.tenantId === this.tenantsService.activeTenantId;
            const isCurrentUser = t.email === this.#currentUser.email || t.email === this.#currentUser.username;
            return !(isCurrentTenant && isCurrentUser);
        });
        const grouped = otherTenant.groupBy(t => t.tenantId);
        return [...grouped.keys()].sort((a, b) => a.localeCompare(b)).map(key => ({ key, value: grouped.get(key) }));
    }
}
