<?php

use App\Models\Currency;
use App\Models\OddsItem;
use App\Models\PlayType;
use App\Models\OddsVersion;
use App\Support\OddsStandardScopes;
use App\Lottery\ConfigVersionStatus;
use Database\Seeders\CurrencySeeder;
use Database\Seeders\PlayTypeSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('syncMissingForVersion adds five scopes from default-only rows', function (): void {
    $this->seed(CurrencySeeder::class);
    $this->seed(PlayTypeSeeder::class);

    $currency = Currency::query()->where('is_bettable', true)->where('is_enabled', true)->orderBy('code')->firstOrFail();

    $version = OddsVersion::query()->create([
        'version_no' => 1,
        'status' => ConfigVersionStatus::Active->value,
        'effective_at' => now(),
        'updated_by' => null,
        'reason' => 'test',
    ]);

    foreach (PlayType::query()->orderBy('play_code')->get() as $pt) {
        OddsItem::query()->create([
            'version_id' => $version->id,
            'play_code' => $pt->play_code,
            'prize_scope' => 'default',
            'odds_value' => 19_500,
            'rebate_rate' => 0.01,
            'commission_rate' => 0,
            'currency_code' => $currency->code,
            'extra_config_json' => null,
        ]);
    }

    OddsStandardScopes::syncMissingForVersion($version);

    $playCount = PlayType::query()->count();
    expect(OddsItem::query()->where('version_id', $version->id)->count())->toBe(
        $playCount * (1 + count(OddsStandardScopes::SCOPE_KEYS)),
    );
    foreach (PlayType::query()->get() as $pt) {
        foreach (OddsStandardScopes::SCOPE_KEYS as $scope) {
            $row = OddsItem::query()
                ->where('version_id', $version->id)
                ->where('play_code', $pt->play_code)
                ->where('currency_code', $currency->code)
                ->where('prize_scope', $scope)
                ->firstOrFail();

            expect((int) $row->odds_value)->toBe(OddsStandardScopes::PRESET_ODDS_BY_SCOPE[$scope]);
            /** @var string $rebate Eloquent `decimal:4` cast */
            $rebate = (string) $row->rebate_rate;
            expect($rebate)->toBe('0.0100');
        }
    }
});
