<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Models\ApiKeyModel;
use App\Services\ActivityLogger;

final class ApiKeyController extends BaseController
{
    public function index(Request $request): Response
    {
        $rows = (new ApiKeyModel())->all();

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success($rows);
        }

        return $this->view('admin/api-keys', [
            'title' => 'API Keys',
            'activeNav' => 'api-keys',
            'breadcrumbs' => [['Home', 'dashboard'], ['Settings', 'integrations'], ['API Keys', 'api-keys']],
            'rows' => $rows,
        ]);
    }

    public function store(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'name' => 'required|string|max:120',
            'scopes' => 'nullable|array',
        ]);

        $result = (new ApiKeyModel())->create($data['name'], $data['scopes'] ?? [], $this->currentUserId());
        ActivityLogger::logAction("API key created: {$data['name']}", 'admin');

        return AjaxResponse::created($result, 'API key created. Copy it now — you will not be able to see it again.');
    }

    public function revoke(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        (new ApiKeyModel())->revoke($id);
        ActivityLogger::logAction('API key revoked', 'admin', 'api_key', $id);

        return AjaxResponse::success(null, 'API key revoked.');
    }
}
