<?php

namespace Migrator\Happytenant\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Migrator\Happytenant\Events\UnitWorkflow as UnitWorkflowEvent;
use Migrator\Happytenant\Notifications\UnitWorkflow as UnitWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class UnitWorkflow
{
    use AsAction;

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

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

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

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

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

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