<?php

namespace App\Classes\Modules\Announcements\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;

use App\Classes\Modules\Announcements\DataTransferObjects\AnnouncementObject;
use App\Classes\Modules\Announcements\Standards\Rules\CanCreateAnnouncement;
use App\Classes\Modules\Announcements\Services\CreatesAnnouncement;
use App\Classes\Modules\Announcements\Processors\AssignAnnouncementToSegmentProcessor;

use App\Http\Resources\AnnouncementResource;
use Carbon\Carbon;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CreateAnnouncementLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification(): array
    {
        return [
            'title' => 'Created Annoucement',
            'message' => 'You have successfully created a new Annoucements'
        ];
    }

    /** @var CanCreateAnnouncement */
    private $canCreateAnnouncement;

    /** @var CreatesAnnoucement */
    private $createsAnnoucement;

    /** @var AssignAnnouncementToSegmentProcessor */
    private $assignAnnouncementToSegmentProcessor;


    /**
     * CreateAnnouncementLogic constructor.
     * @param CanCreateAnnoucement $canCreateAnnoucement
     * @param CreatesAnnoucement $createsAnnoucement
     * @param AssignAnnouncementToSegmentProcessor $assignAnnouncementToSegmentProcessor
     */
    public function __construct(
        CanCreateAnnouncement $canCreateAnnouncement,
        CreatesAnnouncement $createsAnnoucement,
        AssignAnnouncementToSegmentProcessor $assignAnnouncementToSegmentProcessor
    ) {
        $this->canCreateAnnouncement = $canCreateAnnouncement;
        $this->createsAnnoucement = $createsAnnoucement;
        $this->assignAnnouncementToSegmentProcessor = $assignAnnouncementToSegmentProcessor;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function logic(Request $request): JsonResponse
    {
        $annoucement_object = new AnnouncementObject(
            $request->input('title'),
            $request->input('description'),
            Carbon::createFromFormat('d-m-Y', $request->input('starting_on'))->format('Y-m-d H:i:s'),
            Carbon::createFromFormat('d-m-Y', $request->input('ending_on'))->format('Y-m-d H:i:s')
        );

        $this->canCreateAnnouncement->passes($annoucement_object);

        $announcement = $this->createsAnnoucement->execute($annoucement_object);

        $this->assignAnnouncementToSegmentProcessor->execute($announcement);

        return $this->resourceResponse(new AnnouncementResource($announcement));
    }
}
