<?php

namespace App\Services\Ticket;

use App\Models\AgentProfile;
use App\Models\Player;
use Illuminate\Support\Facades\DB;

final class InstantRebateResolver
{
    /**
     * @return array{
     *   base_rebate_rate: float,
     *   player_addon_rebate_rate: float,
     *   final_rebate_rate: float,
     *   inherited_from_agent: bool
     * }
     */
    public function resolveForPlayer(Player $player, string $playCode, float $baseRebateRate): array
    {
        $row = DB::table('player_rebate_profiles')
            ->where('player_id', $player->id)
            ->where('game_type', $playCode)
            ->first();

        if ($row === null) {
            $row = DB::table('player_rebate_profiles')
                ->where('player_id', $player->id)
                ->where('game_type', '*')
                ->first();
        }

        $addonRate = 0.0;
        $inheritedFromAgent = false;

        if ($row !== null && ! (bool) $row->inherit_from_agent) {
            $addonRate = (float) $row->rebate_rate + (float) $row->extra_rebate_rate;
        } else {
            $inheritedFromAgent = true;
            $profile = $player->agent_node_id
                ? AgentProfile::query()->where('agent_node_id', $player->agent_node_id)->first()
                : null;
            $addonRate = (float) ($profile?->default_player_rebate ?? 0);
        }

        return [
            'base_rebate_rate' => $this->normalizeRate($baseRebateRate),
            'player_addon_rebate_rate' => $this->normalizeRate($addonRate),
            'final_rebate_rate' => $this->normalizeRate($baseRebateRate + $addonRate),
            'inherited_from_agent' => $inheritedFromAgent,
        ];
    }

    private function normalizeRate(float $rate): float
    {
        return max(0.0, min(1.0, $rate));
    }
}
