<?php

declare(strict_types=1);

namespace BotGuard\Controllers\Api;

use BotGuard\Core\Request;
use BotGuard\Core\Response;
use BotGuard\Models\VerificationResult;

/**
 * Public REST API (v1), authenticated by API key.
 *
 * Lets customers pull their verification statistics and recent results
 * programmatically. All data is scoped to the user that owns the API key
 * (resolved by ApiKeyAuthMiddleware into the `api_user_id` request attribute).
 */
final class V1Controller
{
    public function __construct(private VerificationResult $results)
    {
    }

    public function stats(Request $request): Response
    {
        $userId = (int) $request->attribute('api_user_id');
        $days = (int) clamp((float) $request->query('days', 30), 1, 365);

        return Response::json([
            'ok'      => true,
            'range'   => ['days' => $days],
            'summary' => $this->results->summary($userId, $days),
        ]);
    }

    public function results(Request $request): Response
    {
        $userId = (int) $request->attribute('api_user_id');
        $limit = (int) clamp((float) $request->query('limit', 50), 1, 500);

        $rows = array_map(static fn (array $r): array => [
            'id'             => (int) $r['id'],
            'created_at'     => $r['created_at'],
            'ip'             => $r['ip'],
            'country'        => $r['country'],
            'browser'        => $r['browser'],
            'os'             => $r['os'],
            'device_type'    => $r['device_type'],
            'score'          => (int) $r['score'],
            'classification' => $r['classification'],
            'decision'       => $r['decision'],
        ], $this->results->recent($userId, $limit));

        return Response::json(['ok' => true, 'count' => count($rows), 'results' => $rows]);
    }
}
