<?php

namespace App\Classes\Modules\Bookings\Services;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Booking;

class CalculatesBookingRefundAmount
{
    public function execute(Booking $booking, int $type, ?string $payment_reference = null): float
    {
        $refundAmounts = $booking->transactions()->payments()->get()->map(function ($payment) use ($type) {
            return $this->calculateRefundAmount($payment, $type);
        });

        $totalRefundAmount = $refundAmounts->sum();

        return $totalRefundAmount;
    }

    public function calculateRefundAmount($payment, int $type): float
    {
        $refundTransactions = $payment->transactions()->refunds()->whereIn('status', [ApprovalStatus::APPROVED]);

        if ($type === 1) {
            return $refundTransactions->selectRaw('sum(amount - service_charge - tax) as sub_total')->get()->sum('sub_total');
        }

        return $refundTransactions->sum('original_amount');
    }
}
