<?php

namespace Daylight\Core\Modules\Payment\Listeners;

use Daylight\Core\Modules\Payment\Contracts\PaymentStatusBuilder;
use Daylight\Core\Modules\Payment\Enums\PaymentStatus;
use Daylight\Core\Modules\Payment\Events\Status\AwaitingPayment;
use Daylight\Core\Modules\Payment\Events\Status\PaymentFailed;
use Daylight\Core\Modules\Payment\Events\Status\PaymentSucceeded;
use Daylight\Core\Modules\Payment\Events\WebhookReceived;

class UpdatePaymentStatus
{
    public function __construct(
        protected PaymentStatusBuilder $paymentStatusBuilder,
    ) {
        //
    }

    public function handle(WebhookReceived $event)
    {
        $orderStatus = $this->paymentStatusBuilder
            ->forOrder($event->order)
            ->get();

        $order = $event->order;

        $order->update([
            'payment_gateway_status' => $orderStatus->getStatus(),
        ]);

        if ($order->payment_gateway_status === $orderStatus->getStatus()) {
            return;
        }

        $order->update([
            'payment_gateway_status' => $orderStatus->getFormattedStatus(),
        ]);

        // Dispatch further actions
        match ($order->payment_gateway_status) {
            PaymentStatus::OPEN,
            PaymentStatus::PENDING,
            PaymentStatus::AUTHORIZED => AwaitingPayment::dispatch($order),

            PaymentStatus::CANCELED,
            PaymentStatus::EXPIRED,
            PaymentStatus::FAILED => PaymentFailed::dispatch($order),

            PaymentStatus::PAID => PaymentSucceeded::dispatch($order),

            default => \Log::error('No actions defined for order status: ' . $order->payment_gateway_status->value),
        };
    }
}
