<?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/dashboard` — top counts, 24h reports histogram (rendered with
 * Chart.js), top reporters, top categories, jobs status. Read-only;
 * manual job triggers land in M12.
 *
 * On API failure the page degrades to "API unreachable; retrying" via
 * the same flash + null-data pattern the layout already supports.
 */
final class DashboardController
{
    public function __construct(
        private readonly Twig $twig,
        private readonly SessionManager $sessions,
        private readonly AdminClient $admin,
    ) {
    }

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

        $stats = null;
        $apiReachable = true;
        try {
            $stats = $this->admin->getDashboardStats($user->userId);
        } catch (ApiException) {
            $apiReachable = false;
        }

        return $this->twig->render($response, 'pages/dashboard.twig', [
            'active_section' => 'dashboard',
            'stats' => $stats,
            'api_reachable' => $apiReachable,
        ]);
    }
}
