<?php

namespace Realestate\Neighbourhood\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Realestate\Neighbourhood\Events\NeighbourhoodWorkflow as NeighbourhoodWorkflowEvent;
use Realestate\Neighbourhood\Notifications\NeighbourhoodWorkflow as NeighbourhoodWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class NeighbourhoodWorkflow
{
    use AsAction;

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

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

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

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

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

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