<?php

use MintyPHP\Http\IntendedUrlService;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Auth\AuthServicesFactory;
use MintyPHP\Support\Flash;

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

$state = trim((string) (requestInput()->queryAll()['state'] ?? ''));
$code = trim((string) (requestInput()->queryAll()['code'] ?? ''));
$error = trim((string) (requestInput()->queryAll()['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;
}

$sessionStore = app(SessionStoreInterface::class);
$sessionStore->set('session_started_at', time());
$sessionStore->set('session_last_activity', time());

if ($tenantSsoService->shouldAutoRememberOnMicrosoftLogin($tenantId)) {
    $authServicesFactory->createRememberMeService()->rememberUser($userId);
}

$intendedUrlService = app(IntendedUrlService::class);
Router::redirect($intendedUrlService->retrieveAndForget($sessionStore));
