<?php

declare(strict_types=1);

namespace App\Controllers;

use App\ApiClient\AdminClient;
use App\ApiClient\ApiException;
use App\Auth\SessionManager;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Views\Twig;

/**
 * `/app/me` — render the current acting identity.
 *
 * Truth source for role/email/display_name is the api's
 * `GET /api/v1/admin/me`. The session caches a copy for fast page
 * rendering, but each visit refreshes from the api so role changes
 * elsewhere propagate without a re-login.
 */
final class MeController
{
    public function __construct(
        private readonly Twig $twig,
        private readonly SessionManager $sessions,
        private readonly AdminClient $admin,
    ) {
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $sessionUser = $this->sessions->getUser();
        if ($sessionUser === null) {
            return $response->withStatus(302)->withHeader('Location', '/login');
        }

        $apiSource = $sessionUser->source;
        $email = $sessionUser->email;
        $displayName = $sessionUser->displayName;
        $role = $sessionUser->role;
        $apiReachable = true;

        try {
            $live = $this->admin->getMe($sessionUser->userId);
            $email = $live->email ?? $email;
            $displayName = $live->displayName !== '' ? $live->displayName : $displayName;
            $role = $live->role;
            $apiSource = $live->effectiveSource();
        } catch (ApiException) {
            $apiReachable = false;
        }

        return $this->twig->render($response, 'pages/me.twig', [
            'user_id' => $sessionUser->userId,
            'email' => $email,
            'display_name' => $displayName,
            'role' => $role,
            'source' => $apiSource,
            'api_reachable' => $apiReachable,
        ]);
    }
}
