<?php

namespace Bixo\Feed\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Feed\Events\FeedWorkflow as FeedWorkflowEvent;
use Bixo\Feed\Notifications\FeedWorkflow as FeedWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class FeedWorkflow
{
    use AsAction;

    private $allowedTransitions = [
        'before' => [],
        'after' => ['publish', 'submit', 'approve'],
    ];

    public function handle(FeedWorkflowEvent $event)
    {
        $function = Str::camel($event->transition);
        return $this->$function($event);
    }

    /**
     * Sends a notification to the client when the $feed is submitted.
     *
     * @param FeedWorkflowEvent $event The event object.
     * @return void
     */
    public function submit(FeedWorkflowEvent $event)
    {
        $client = $event->feed->client;
        Notification::send($client, new FeedWorkflowNotification($event));
    }

    /**
     * Sends a notification to the client when the $feed is published.
     *
     * @param FeedWorkflowEvent $event The event object.
     * @return void
     */
    public function publish(FeedWorkflowEvent $event)
    {
        $client = $event->feed->client;
        Notification::send($client, new FeedWorkflowNotification($event));
    }

    /**
     * Sends a notification to the client when the $feed is approved.
     *
     * @param FeedWorkflowEvent $event The event object.
     * @return void
     */
    public function approve(FeedWorkflowEvent $event)
    {
        $client = $event->feed->client;
        Notification::send($client, new FeedWorkflowNotification($event));
    }

    /**
     * Handles the $feed workflow event as a listener.
     *
     * @param FeedWorkflowEvent $event The event object.
     * @return void
     */
    public function asListener(FeedWorkflowEvent $event)
    {
        if (($event->when == 'before' &&
            in_array($event->transition, $this->allowedTransitions['before']) ||
            $event->when == 'after' &&
            in_array($event->transition, $this->allowedTransitions['after']))
        ) {
            return $this->handle($event);
        }
    }
}