<?php

namespace App\Services;

use App\Models\AccessRequests;

class RconAccessGrantor
{
    public function __construct(
        private readonly MinecraftRconClient $rconClient,
    ) {}

    public function grant(AccessRequests $accessRequest): string
    {
        return $this->rconClient->command($this->commandFor($accessRequest->game_username));
    }

    private function commandFor(string $gameUsername): string
    {
        $accessCommand = (string) config('rcon.access_command', 'whitelist add {username}');

        if (! str_contains($accessCommand, '{username}')) {
            $accessCommand = trim($accessCommand).' {username}';
        }

        return str_replace('{username}', $gameUsername, $accessCommand);
    }
}
