<?php

declare(strict_types=1);

namespace BotGuard\Controllers\User;

use BotGuard\Core\Auth;
use BotGuard\Core\Controller;
use BotGuard\Core\Csrf;
use BotGuard\Core\Request;
use BotGuard\Core\Response;
use BotGuard\Core\Session;
use BotGuard\Core\View;
use BotGuard\Models\ApiKey;
use BotGuard\Models\AuditLog;

/**
 * User-facing API key management. The full key is displayed exactly once,
 * immediately after creation (only its hash is stored).
 */
final class ApiKeyController extends Controller
{
    public function __construct(
        View $view,
        Session $session,
        Csrf $csrf,
        Request $request,
        private Auth $auth,
        private ApiKey $keys,
        private AuditLog $audit,
    ) {
        parent::__construct($view, $session, $csrf, $request);
    }

    public function index(Request $request): Response
    {
        return $this->render('user.api_keys', [
            'title'   => 'API Keys',
            'keys'    => $this->keys->forUser((int) $this->auth->id()),
            'newKey'  => $this->session->getFlash('new_api_key'),
        ]);
    }

    public function create(Request $request): Response
    {
        $name = trim((string) $request->input('name', 'API key'));
        [, $plain] = $this->keys->createForUser((int) $this->auth->id(), $name);

        $this->audit->record($this->auth->id(), 'api_key.created', $request->ip(), ['name' => $name]);
        $this->session->flash('new_api_key', $plain);

        return $this->redirect('/dashboard/api-keys', 'success', 'API key created. Copy it now — it will not be shown again.');
    }

    public function revoke(Request $request): Response
    {
        $id = (int) $request->input('id');
        $this->keys->revokeForUser($id, (int) $this->auth->id());
        $this->audit->record($this->auth->id(), 'api_key.revoked', $request->ip(), ['id' => $id]);

        return $this->redirect('/dashboard/api-keys', 'success', 'API key revoked.');
    }
}
