<?php
declare(strict_types=1);

namespace App\Modules\Printing;

use App\Core\Http\Request;
use App\Core\Http\Response;

final class ApiKeyMiddleware
{
    public function __construct(
        private readonly PrintApiKeyRepository $apiKeys
    ) {
    }

    public function __invoke(Request $request, callable $next): Response
    {
        $apiKey = $request->header('X-Api-Key');
        if ($apiKey === '') {
            return Response::json(['error' => 'Unauthorized'], 401);
        }

        $keyHash = hash('sha256', $apiKey);
        $record = $this->apiKeys->findByKeyHash($keyHash);

        if ($record === null || (int) ($record['is_active'] ?? 0) !== 1) {
            return Response::json(['error' => 'Unauthorized'], 401);
        }

        $this->apiKeys->updateLastUsed((int) $record['id']);

        $result = $next($request);
        if ($result instanceof Response) {
            return $result;
        }

        if (is_array($result)) {
            return Response::json($result);
        }

        return Response::html((string) $result);
    }
}
