<?php

namespace Bixo\Message\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Message\Events\MessageWorkflow as MessageWorkflowEvent;
use Bixo\Message\Notifications\MessageWorkflow as MessageWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class MessageWorkflow
{
    use AsAction;

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

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

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

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

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

    /**
     * Handles the $message workflow event as a listener.
     *
     * @param MessageWorkflowEvent $event The event object.
     * @return void
     */
    public function asListener(MessageWorkflowEvent $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);
        }
    }
}