package com.mvrent.carrental.service;

import com.mvrent.carrental.model.Car;
import com.mvrent.carrental.model.Vendor;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * Resolves the organization commission percent for a car using a three-tier
 * fallback: per-vehicle override → per-vendor rate → global default.
 * Owned cars (no vendor) carry no commission.
 */
@Service
@RequiredArgsConstructor
public class CommissionService {

    private final ConfigService configService;

    /** Commission percent that applies to the given car (0 for owned cars). */
    public BigDecimal resolvePercent(Car car) {
        if (car == null || car.getVendor() == null) {
            return BigDecimal.ZERO;
        }
        if (car.getCommissionPercentOverride() != null) {
            return car.getCommissionPercentOverride();
        }
        Vendor vendor = car.getVendor();
        if (vendor.getCommissionPercent() != null) {
            return vendor.getCommissionPercent();
        }
        return configService.getSystemConfig().getDefaultCommissionPercent();
    }

    /** Commission amount on a gross figure for the given car. */
    public BigDecimal commissionAmount(Car car, BigDecimal gross) {
        if (gross == null) return BigDecimal.ZERO;
        return gross.multiply(resolvePercent(car))
                .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
    }
}
