<?php

namespace App\Services;

use Carbon\Carbon;

class RefundPolicyService
{
    public function calculate(object $booking, string $reason = 'customer_cancelled'): array
    {
        $payable = (float) $booking->payable_total;

        if ($reason === 'professional_unavailable' || $reason === 'professional_no_show') {
            return ['refund_amount' => $payable, 'policy' => 'Full refund or free reschedule when Pro is unavailable.'];
        }

        if ($booking->booking_type === 'instant') {
            $amount = in_array($booking->assignment_status, ['unassigned', 'assigning'], true) ? $payable : 0;

            return ['refund_amount' => $amount, 'policy' => 'Instant bookings refund only before assignment/service start.'];
        }

        $startAt = Carbon::parse($booking->scheduled_start_at);
        $hours = now()->diffInMinutes($startAt, false) / 60;

        if ($booking->booking_type === 'recurring') {
            return $hours >= 3
                ? ['refund_amount' => $payable, 'policy' => 'Recurring session cancelled at least 3 hours before slot.']
                : ['refund_amount' => 0, 'policy' => 'Recurring late cancellation or no-show fee equals session cost.'];
        }

        if ($hours > 6) {
            return ['refund_amount' => $payable, 'policy' => 'Scheduled booking cancelled more than 6 hours before slot.'];
        }

        if ($hours >= 3) {
            return ['refund_amount' => round($payable * 0.5, 2), 'policy' => 'Scheduled booking cancelled 3 to 6 hours before slot.'];
        }

        return ['refund_amount' => 0, 'policy' => 'Scheduled booking cancelled less than 3 hours before slot or customer no-show.'];
    }
}
