<?php


namespace App\Model\Facades\Writers;


use App\Model\Entities\Dkp;
use App\Model\Facades\Readers\SiteReader;
use App\Model\Facades\Readers\UserReader;
use App\Model\Services\DkpService;
use Throwable;

class DkpWriter extends BaseWriter
{
    /** @var  DkpService */
    protected $dkpService;
    /** @var  SiteReader */
    protected $siteReader;
    /** @var  UserReader */
    protected $userReader;

    public function inject(DkpService $dkpService, SiteReader $siteReader, UserReader $userReader)
    {
        $this->dkpService = $dkpService;
        $this->siteReader = $siteReader;
        $this->userReader = $userReader;
    }

    public function grantDkp($guild, $grantedTo, string $reason, int $amount) : Dkp
    {
        $site = $this->siteReader->validateSite($guild);
        $player = $this->userReader->validateUser($grantedTo);

        try {
            $this->beginTransaction();
            $dkp = $this->dkpService->grantDkp($site, $this->getLoggedInUser(), $player, $reason, $amount);
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }

        return $dkp;
    }
}