<?php

namespace App\Services;

use App\Enums\AccessRequestStatus;
use App\Models\AccessRequests;
use App\Models\User;
use DomainException;
use Illuminate\Support\Facades\DB;

class AccessRequestApprover
{
    public function __construct(
        private readonly RconAccessGrantor $rconAccessGrantor,
    ) {}

    public function approve(AccessRequests $accessRequest, ?User $reviewer = null): string
    {
        $accessRequest->refresh();

        if ($accessRequest->status !== AccessRequestStatus::PENDING) {
            throw new DomainException('Only pending access requests can be accepted.');
        }

        $output = $this->rconAccessGrantor->grant($accessRequest);

        DB::transaction(function () use ($accessRequest, $reviewer): void {
            $accessRequest->forceFill([
                'status' => AccessRequestStatus::ACCEPTED,
                'reviewed_by' => $reviewer?->getKey(),
                'reviewed_at' => now(),
            ])->save();
        });

        return $output;
    }
}
