<?php

namespace App\Services;

use App\Models\DepositRule;

class DepositCalculator
{
    public static function calculate(int $loanAmount): int
    {
        $rule = DepositRule::where('is_active', 1)
            ->where('min_amount', '<=', $loanAmount)
            ->where(function ($q) use ($loanAmount) {
                $q->whereNull('max_amount')
                  ->orWhere('max_amount', '>=', $loanAmount);
            })
            ->orderByDesc('min_amount')
            ->first();

        if (! $rule) {
            return 500; // fallback
        }

        if ($rule->calc_type === 'flat') {
            return (int) round($rule->value);
        }

        return (int) round($loanAmount * ($rule->value / 100));
    }
}
