<?php

namespace App\Classes\Modules\Announcements\Processors;

use App\Classes\Modules\Announcements\Services\AssignsAnnouncementToSegment;
use App\Classes\Modules\Announcements\Standards\Rules\CanAssignSegment;
use App\Classes\Modules\Segments\Services\FetchesSegment;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Models\Announcement;
use Illuminate\Database\Eloquent\Model;

class AssignAnnouncementToSegmentProcessor
{

    /** @var CanAssignSegment */
    private $canAssignSegment;

    /** @var FetchesSegment */
    private $fetchesSegment;

    /** @var AssignAnnouncementToSegment */
    private $assignsAnnouncementToSegment;



    /**
     * AssignAnnouncementToSegmentProcessor constructor.
     * @param CanAssignSegment $canAssignSegment
     * @param AssignAnnouncementToSegment $assignsAnnouncementToSegment
     * @param FetchesSegment $fetchesSegment
     */
    public function __construct(CanAssignSegment $canAssignSegment, FetchesSegment $fetchesSegment, AssignsAnnouncementToSegment $assignsAnnouncementToSegment)
    {
        $this->canAssignSegment = $canAssignSegment;
        $this->assignsAnnouncementToSegment = $assignsAnnouncementToSegment;
        $this->fetchesSegment = $fetchesSegment;
    }


    /**
     * @param Announcement $announcement
     * @param int|null $segmentId
     * @return Model
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function execute(Announcement $announcement, ?int $segmentId = SegmentConstants::STANDARD_SEGMENT): Model
    {
        $this->canAssignSegment->passes();

        $segment = $this->fetchesSegment->execute(['id' => $segmentId]);

        return $this->assignsAnnouncementToSegment->execute($announcement, $segment);
    }
}
