<?php

namespace Eform\Test\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Eform\Test\Events\TestWorkflow as TestWorkflowEvent;
use Eform\Test\Notifications\TestWorkflow as TestWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class TestWorkflow
{
    use AsAction;

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

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

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

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

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

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