<?php
declare(strict_types=1);

namespace App\Framework\Http\Api;

use App\Framework\Attributes\Route;
use App\Framework\Http\Method;
use App\Framework\Http\Status;
use App\Framework\Logging\DefaultLogger;
use App\Framework\Logging\LogLevel;
use App\Framework\Router\Result\JsonResult;

/**
 * API-Controller für Client-Logging.
 * Ermöglicht es dem Frontend, Logs an den Server zu senden und dabei die Request-ID zu verwenden.
 */
final readonly class ClientLogController
{
    public function __construct(
        private DefaultLogger $logger
    ) {}

    #[Route(path: '/api/log', method: Method::POST)]
    public function __invoke(ClientLogRequest $request): JsonResult
    {
        // Log-Level aus dem Client konvertieren
        $level = match ($request->level) {
            'error' => LogLevel::ERROR,
            'warn' => LogLevel::WARNING,
            'info' => LogLevel::INFO,
            default => LogLevel::DEBUG,
        };

        // Log mit Kontext schreiben
        $this->logger->log($level, "Client: {$request->message}", [
            'client' => true,
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
            'context' => $request->context ?? [],
        ]);

        return new JsonResult([
            'success' => true,
        ], Status::OK);
    }
}
