<?php

namespace Bixo\Payment\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Payment\Events\GatewayWorkflow as GatewayWorkflowEvent;
use Bixo\Payment\Notifications\GatewayWorkflow as GatewayWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class GatewayWorkflow
{
    use AsAction;

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

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

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

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

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

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