<?php

namespace App\Services\Player;

use App\Models\AgentNode;
use Illuminate\Support\Facades\DB;
use App\Services\Agent\RebateLimitValidator;

final class PlayerRebateProfileService
{
    public function __construct(
        private readonly RebateLimitValidator $rebateLimitValidator,
    ) {}

    /**
     * @param  list<array{game_type: string, rebate_rate?: float, extra_rebate_rate?: float, inherit_from_agent?: bool}>  $profiles
     */
    public function syncProfiles(int $playerId, AgentNode $agent, array $profiles): void
    {
        if ($profiles === []) {
            return;
        }

        $now = now();
        foreach ($profiles as $row) {
            $gameType = trim((string) ($row['game_type'] ?? '*')) ?: '*';
            $inherit = (bool) ($row['inherit_from_agent'] ?? false);
            $rebateRate = (float) ($row['rebate_rate'] ?? 0) / 100;
            $extraRate = (float) ($row['extra_rebate_rate'] ?? 0) / 100;

            if (! $inherit) {
                $this->rebateLimitValidator->assertPlayerRebateWithinAgent($agent, $rebateRate, $extraRate);
            }

            DB::table('player_rebate_profiles')->updateOrInsert(
                ['player_id' => $playerId, 'game_type' => $gameType],
                [
                    'inherit_from_agent' => $inherit,
                    'rebate_rate' => $inherit ? 0 : $rebateRate,
                    'extra_rebate_rate' => $inherit ? 0 : $extraRate,
                    'updated_at' => $now,
                    'created_at' => $now,
                ],
            );
        }
    }

    /**
     * @return list<array{game_type: string, rebate_rate: float, extra_rebate_rate: float, inherit_from_agent: bool}>
     */
    public function listForPlayer(int $playerId): array
    {
        return DB::table('player_rebate_profiles')
            ->where('player_id', $playerId)
            ->orderBy('game_type')
            ->get()
            ->map(static fn (object $row): array => [
                'game_type' => (string) $row->game_type,
                'rebate_rate' => round((float) $row->rebate_rate * 100, 4),
                'extra_rebate_rate' => round((float) $row->extra_rebate_rate * 100, 4),
                'inherit_from_agent' => (bool) $row->inherit_from_agent,
            ])
            ->all();
    }
}
