<?php

namespace Database\Seeders;

use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CourtSeeder extends Seeder
{
    public function run(): void
    {
        DB::disableQueryLog();
        Model::unsetEventDispatcher();

        $chunkSize = 100;
        $tableName = 'courts';
        $now = CarbonImmutable::now();
        $startDate = $now->subMonths(12);

        $games = DB::table('games')->get(['id', 'name']);
        if ($games->isEmpty()) {
            $this->command->warn('No games found. Run GameSeeder first.');
            return;
        }

        $courtLabelsEn = ['Main', 'Secondary', 'Indoor', 'Outdoor', 'Premium'];
        $courtLabelsAr = ['رئيسي', 'ثانوي', 'داخلي', 'خارجي', 'مميز'];
        $rows = [];
        $idx = 0;

        foreach ($games as $game) {
            $nameData = json_decode($game->name, true) ?: ['en' => 'Court', 'ar' => 'ملعب'];
            $nameEn = ($nameData['en'] ?? 'Court') . ' - ' . $courtLabelsEn[0] . ' ';
            $nameAr = ($nameData['ar'] ?? 'ملعب') . ' - ' . $courtLabelsAr[0] . ' ';
            $courtsPerGame = rand(2, 4);
            for ($c = 0; $c < $courtsPerGame; $c++) {
                $createdAt = CarbonImmutable::createFromTimestamp(
                    rand($startDate->timestamp, $now->timestamp)
                )->setTime(12, 0, 0)->format('Y-m-d H:i:s');
                $labelIdx = $c % count($courtLabelsEn);
                $rows[] = [
                    'name'        => json_encode([
                        'en' => ($nameData['en'] ?? 'Court') . ' - ' . $courtLabelsEn[$labelIdx] . ' ' . ($c + 1),
                        'ar' => ($nameData['ar'] ?? 'ملعب') . ' - ' . $courtLabelsAr[$labelIdx] . ' ' . ($c + 1),
                    ]),
                    'game_id'     => $game->id,
                    'description' => json_encode(['en' => 'Professional standard court.', 'ar' => 'ملعب احترافي بمعايير عالية.']),
                    'is_active'   => rand(0, 10) > 1 ? 1 : 0,
                    'created_at'  => $createdAt,
                    'updated_at'  => $createdAt,
                ];
                $idx++;
            }

            if (count($rows) >= $chunkSize) {
                DB::table($tableName)->insert($rows);
                $rows = [];
            }
        }

        if (!empty($rows)) {
            DB::table($tableName)->insert($rows);
        }

        $this->command->info('Courts seeded: ' . ($idx) . ' records');
    }
}
