<?php

use MintyPHP\Router;
use MintyPHP\Service\Auth\AuthServicesFactory;
use MintyPHP\Support\Flash;

$authServicesFactory = app(AuthServicesFactory::class);
$tenantSsoService = $authServicesFactory->createTenantSsoService();
$microsoftOidcService = $authServicesFactory->createMicrosoftOidcService();

$tenantSlug = trim((string) (requestInput()->queryAll()['tenant'] ?? ''));
if ($tenantSlug === '') {
    Flash::error(t('Tenant login link is invalid'), 'login', 'tenant_login_invalid');
    Router::redirect('login');
    return;
}

$tenant = $tenantSsoService->findTenantByLoginSlug($tenantSlug);
if (!$tenant) {
    Flash::error(t('Tenant login link is invalid'), 'login', 'tenant_login_invalid');
    Router::redirect('login');
    return;
}
$tenantSlug = $tenantSsoService->tenantLoginSlug($tenant);
$loginTarget = $tenantSlug !== '' ? ('login?tenant=' . rawurlencode($tenantSlug)) : 'login';

$configResult = $tenantSsoService->getEffectiveMicrosoftProviderConfig($tenant);
if (!($configResult['ok'] ?? false)) {
    Flash::error(t('Microsoft login is not available for this tenant'), $loginTarget, 'microsoft_login_not_available');
    Router::redirect($loginTarget);
    return;
}

$authResult = $microsoftOidcService->startAuthorization($tenant, $configResult['config'] ?? []);
if (!($authResult['ok'] ?? false)) {
    Flash::error(t('Microsoft login could not be started'), $loginTarget, 'microsoft_login_start_failed');
    Router::redirect($loginTarget);
    return;
}

$url = trim((string) ($authResult['url'] ?? ''));
if ($url === '') {
    Flash::error(t('Microsoft login could not be started'), $loginTarget, 'microsoft_login_start_failed');
    Router::redirect($loginTarget);
    return;
}

Router::redirect($url);
