<?php

namespace App\Services\Agent;

use App\Models\AgentNode;
use App\Models\AgentProfile;
use Illuminate\Validation\ValidationException;

final class ShareRateValidator
{
    public function assertChildWithinParent(AgentNode $parent, float $childTotalShareRate, string $field = 'total_share_rate'): void
    {
        $parentRate = $this->totalShareRateForNode($parent);
        if ($childTotalShareRate > $parentRate) {
            throw ValidationException::withMessages([
                $field => ['exceeds_parent'],
            ]);
        }
        if ($childTotalShareRate < 0 || $childTotalShareRate > 100) {
            throw ValidationException::withMessages([
                $field => ['invalid_range'],
            ]);
        }
    }

    public function assertRelativeShareWithinBounds(float $relativeShareRate, string $field = 'relative_share_rate'): void
    {
        if ($relativeShareRate < 0 || $relativeShareRate > 100) {
            throw ValidationException::withMessages([
                $field => ['invalid_range'],
            ]);
        }
    }

    public function totalShareRateForNode(AgentNode $node): float
    {
        $profile = AgentProfile::query()->where('agent_node_id', $node->id)->first();

        return $profile !== null ? (float) $profile->total_share_rate : 100.0;
    }
}
