<?php

namespace Bixo\Developer\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Developer\Events\DeveloperWorkflow as DeveloperWorkflowEvent;
use Bixo\Developer\Notifications\DeveloperWorkflow as DeveloperWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class DeveloperWorkflow
{
    use AsAction;

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

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

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

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

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

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