<?php

namespace Bixo\Team\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Team\Events\UserWorkflow as UserWorkflowEvent;
use Bixo\Team\Notifications\UserWorkflow as UserWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class UserWorkflow
{
    use AsAction;

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

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

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

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

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

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