<?php

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

$authServicesFactory = new AuthServicesFactory();
$authService = $authServicesFactory->createAuthService();
$ssoUserLinkService = $authServicesFactory->createSsoUserLinkService();
$tenantSsoService = $authServicesFactory->createTenantSsoService();
$microsoftOidcService = $authServicesFactory->createMicrosoftOidcService();

$state = trim((string) ($_GET['state'] ?? ''));
$code = trim((string) ($_GET['code'] ?? ''));
$error = trim((string) ($_GET['error'] ?? ''));

if ($error !== '') {
    Flash::error(t('Microsoft login was cancelled or failed'), 'login', 'microsoft_login_error');
    Router::redirect('login');
    return;
}

$callbackResult = $microsoftOidcService->handleCallback($state, $code);
if (!($callbackResult['ok'] ?? false)) {
    Flash::error(t('Microsoft login failed'), 'login', 'microsoft_login_failed');
    Router::redirect('login');
    return;
}

$tenant = $callbackResult['tenant'] ?? null;
if (!is_array($tenant)) {
    Flash::error(t('Microsoft login failed'), 'login', 'microsoft_login_failed');
    Router::redirect('login');
    return;
}

$linkResult = $ssoUserLinkService->linkOrProvisionMicrosoftUser(
    $tenant,
    is_array($callbackResult['claims'] ?? null) ? $callbackResult['claims'] : []
);
if (!($linkResult['ok'] ?? false)) {
    $tenantSlug = $tenantSsoService->tenantLoginSlug($tenant);
    $loginTarget = $tenantSlug !== '' ? ('login?tenant=' . rawurlencode($tenantSlug)) : 'login';
    Flash::error(t('Microsoft login is not allowed for this account'), $loginTarget, 'microsoft_login_not_allowed');
    Router::redirect($loginTarget);
    return;
}

$userId = (int) ($linkResult['user_id'] ?? 0);
$tenantId = (int) ($tenant['id'] ?? 0);
$loginResult = $authService->loginUserById($userId, $tenantId, 'microsoft');
if (!($loginResult['ok'] ?? false)) {
    $tenantSlug = $tenantSsoService->tenantLoginSlug($tenant);
    $loginTarget = $tenantSlug !== '' ? ('login?tenant=' . rawurlencode($tenantSlug)) : 'login';
    Flash::error(t('Microsoft login failed'), $loginTarget, 'microsoft_login_failed');
    Router::redirect($loginTarget);
    return;
}

Router::redirect('admin');
