<?php

namespace Database\Seeders;

use Carbon\Carbon;
use App\Models\Draw;
use App\Models\RiskPool;
use App\Lottery\DrawStatus;
use App\Models\DrawResultItem;
use App\Models\DrawResultBatch;
use App\Models\SettlementBatch;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Lottery\DrawResultBatchStatus;
use App\Lottery\SettlementBatchStatus;
use App\Services\Draw\DrawPrizeLayout;

/**
 * 【多场景演示】额外写入几条 **非大厅当期** 的期号与数据，便于列表、开奖结果、结算摘要等联调。
 *
 * - `…-996`：已结算 + 已发布开奖批次 + 完整 23 条 `draw_result_items` + 一条已完成结算批次 + 少量风险池
 * - `…-995`：未开始的 pending 期（将来开售）
 *
 * ```bash
 * php artisan db:seed --class="Database\\Seeders\\DashboardSecondaryScenariosSeeder"
 * ```
 */
final class DashboardSecondaryScenariosSeeder extends Seeder
{
    public function run(): void
    {
        if (app()->environment('production')) {
            return;
        }

        $now = Carbon::now()->utc();
        $biz = $now->format('Y-m-d');
        $ymd = str_replace('-', '', $biz);

        DB::transaction(function () use ($biz, $ymd, $now): void {
            $this->seedSettledShowcase($biz, $ymd, $now);
            $this->seedPendingFuture($biz, $ymd, $now);
        });

        $this->command?->info('DashboardSecondaryScenariosSeeder: 已写入 -996 settled 与 -995 pending 演示期。');
    }

    private function seedSettledShowcase(string $biz, string $ymd, Carbon $now): void
    {
        $drawTime = $now->copy()->subHours(6);

        $draw = Draw::query()->updateOrCreate(
            ['draw_no' => $ymd.'-996'],
            [
                'business_date' => $biz,
                'sequence_no' => 996,
                'status' => DrawStatus::Settled->value,
                'start_time' => $drawTime->copy()->subMinutes(30),
                'close_time' => $drawTime->copy()->subSeconds(30),
                'draw_time' => $drawTime,
                'cooling_end_time' => $drawTime->copy()->addMinutes(10),
                'result_source' => 'rng',
                'current_result_version' => 1,
                'settle_version' => 1,
                'is_reopened' => false,
            ],
        );

        $batch = DrawResultBatch::query()->updateOrCreate(
            [
                'draw_id' => $draw->id,
                'result_version' => 1,
            ],
            [
                'source_type' => 'rng',
                'rng_seed_hash' => hash('sha256', 'dashboard-secondary-996'),
                'raw_seed_encrypted' => null,
                'status' => DrawResultBatchStatus::Published->value,
                'created_by' => null,
                'confirmed_by' => null,
                'confirmed_at' => $drawTime,
            ],
        );

        DrawResultItem::query()->where('result_batch_id', $batch->id)->delete();

        foreach (DrawPrizeLayout::slots() as $i => $slot) {
            $n = (($i + 7) * 401) % 10_000;
            $num = str_pad((string) $n, 4, '0', STR_PAD_LEFT);
            DrawResultItem::query()->create([
                'draw_id' => $draw->id,
                'result_batch_id' => $batch->id,
                'prize_type' => $slot['prize_type'],
                'prize_index' => $slot['prize_index'],
                'number_4d' => $num,
                'suffix_3d' => substr($num, -3),
                'suffix_2d' => substr($num, -2),
                'head_digit' => (int) substr($num, 0, 1),
                'tail_digit' => (int) substr($num, 3, 1),
            ]);
        }

        SettlementBatch::query()->updateOrCreate(
            [
                'draw_id' => $draw->id,
                'settle_version' => 1,
            ],
            [
                'result_batch_id' => $batch->id,
                'status' => SettlementBatchStatus::Completed->value,
                'total_ticket_count' => 12,
                'total_win_count' => 3,
                'total_payout_amount' => 450_000,
                'total_jackpot_payout_amount' => 20_000,
                'started_at' => $drawTime->copy()->addMinutes(2),
                'finished_at' => $drawTime->copy()->addMinutes(5),
            ],
        );

        $pools = [
            ['2468', 1_000_000, 400_000, 0],
            ['1357', 800_000, 200_000, 0],
            ['90X9', 600_000, 540_000, 0],
            ['9X9X', 400_000, 160_000, 0],
            ['12AB', 300_000, 90_000, 0],
            ['8888', 200_000, 200_000, 1],
        ];
        foreach ($pools as [$num, $cap, $locked, $sold]) {
            RiskPool::query()->updateOrCreate(
                ['draw_id' => $draw->id, 'normalized_number' => $num],
                [
                    'total_cap_amount' => $cap,
                    'locked_amount' => $locked,
                    'remaining_amount' => max(0, $cap - $locked),
                    'sold_out_status' => $sold,
                    'version' => 1,
                ],
            );
        }
    }

    private function seedPendingFuture(string $biz, string $ymd, Carbon $now): void
    {
        $start = $now->copy()->addHours(8);
        $close = $start->copy()->addMinutes(10);
        $drawT = $close->copy()->addSeconds(30);

        Draw::query()->updateOrCreate(
            ['draw_no' => $ymd.'-995'],
            [
                'business_date' => $biz,
                'sequence_no' => 995,
                'status' => DrawStatus::Pending->value,
                'start_time' => $start,
                'close_time' => $close,
                'draw_time' => $drawT,
                'cooling_end_time' => null,
                'result_source' => null,
                'current_result_version' => 0,
                'settle_version' => 0,
                'is_reopened' => false,
            ],
        );
    }
}
