<?php

namespace App\Rules;

use App\Traits\FormatAsCurrency;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class CashbackDoesNotExceedValuation implements ValidationRule
{
    use FormatAsCurrency;

    public function __construct(
        private readonly float $retailPrice,
        private readonly float $outstandingFinance
    ) {
    }

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if ((int) $value === 0) {
            return;
        }

        $maxCashback = $this->retailPrice - $this->outstandingFinance;

        if ((float) $value > $maxCashback) {
            $fail(__('deal_builder.cashback_exceeds_valuation', [
                'max' => $this->asCurrency($maxCashback, null, 2),
            ]));
        }
    }
}
