<?php

namespace Database\Seeders;

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

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

        $tableName = 'academies';
        $chunkSize = 100;
        $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;
        }

        $academyNamesEn = ['Elite Academy', 'Future Stars', 'Pro Skills', 'Champions Club', 'Junior Academy'];
        $academyNamesAr = ['أكاديمية النخبة', 'نجوم المستقبل', 'مهارات المحترفين', 'نادي الأبطال', 'أكاديمية الناشئين'];

        $rows = [];
        $total = 0;

        foreach ($games as $game) {
            $decoded = json_decode($game->name, true) ?: ['en' => 'Game', 'ar' => 'لعبة'];
            $baseEn  = $decoded['en'] ?? 'Game';
            $baseAr  = $decoded['ar'] ?? 'لعبة';

            $academiesPerGame = 1;
            for ($i = 0; $i < $academiesPerGame; $i++) {
                $createdAt = CarbonImmutable::createFromTimestamp(
                    rand($startDate->timestamp, $now->timestamp)
                )->setTime(12, 0, 0)->format('Y-m-d H:i:s');

                $nameIdx = $i % count($academyNamesEn);
                $rows[] = [
                    'game_id'     => $game->id,
                    'name'        => json_encode([
                        'en' => $baseEn . ' ' . $academyNamesEn[$nameIdx],
                        'ar' => $baseAr . ' ' . $academyNamesAr[$nameIdx],
                    ]),
                    'description' => json_encode([
                        'en' => 'Training academy focused on ' . $baseEn . ' fundamentals and advanced skills.',
                        'ar' => 'أكاديمية تدريب تركز على أساسيات ' . $baseAr . ' والمهارات المتقدمة.',
                    ]),
                    'image'       => null,
                    'is_active'   => rand(0, 10) > 1 ? 1 : 0,
                    'created_at'  => $createdAt,
                    'updated_at'  => $createdAt,
                ];
                $total++;

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

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

        $this->command->info("Academies seeded: {$total} records");
    }
}

