<?php

namespace Database\Seeders;

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

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

        $chunkSize = 50;
        $tableName = 'cities';

        $saudiArabia = DB::table('countries')->where('code', 'SA')->first();

        if (!$saudiArabia) {
            $this->command->warn('Saudi Arabia country not found. Run CountrySeeder first.');
            return;
        }

        $cities = [
            ['name' => ['en' => 'Riyadh', 'ar' => 'الرياض']],
            ['name' => ['en' => 'Jeddah', 'ar' => 'جدة']],
            ['name' => ['en' => 'Mecca', 'ar' => 'مكة المكرمة']],
            ['name' => ['en' => 'Medina', 'ar' => 'المدينة المنورة']],
            ['name' => ['en' => 'Dammam', 'ar' => 'الدمام']],
            ['name' => ['en' => 'Khobar', 'ar' => 'الخبر']],
            ['name' => ['en' => 'Dhahran', 'ar' => 'الظهران']],
            ['name' => ['en' => 'Tabuk', 'ar' => 'تبوك']],
            ['name' => ['en' => 'Abha', 'ar' => 'أبها']],
            ['name' => ['en' => 'Khamis Mushait', 'ar' => 'خميس مشيط']],
            ['name' => ['en' => 'Taif', 'ar' => 'الطائف']],
            ['name' => ['en' => 'Buraidah', 'ar' => 'بريدة']],
            ['name' => ['en' => 'Najran', 'ar' => 'نجران']],
            ['name' => ['en' => 'Jizan', 'ar' => 'جيزان']],
            ['name' => ['en' => 'Yanbu', 'ar' => 'ينبع']],
        ];

        $rows = [];

        $upsert = function (array $records) use ($tableName) {
            foreach ($records as $record) {
                DB::table($tableName)->updateOrInsert(
                    ['country_id' => $record['country_id'], 'name' => $record['name']],
                    $record
                );
            }
        };

        foreach ($cities as $city) {
            $now = CarbonImmutable::now()
                ->subMonths(rand(1, 6))
                ->subDays(rand(1, 30));

            $rows[] = [
                'country_id' => $saudiArabia->id,
                'name'       => json_encode($city['name'], JSON_UNESCAPED_UNICODE),
                'is_active'  => true,
                'created_at' => $now,
                'updated_at' => $now,
            ];

            if (count($rows) >= $chunkSize) {
                $upsert($rows);
                $rows = [];
            }
        }

        if (!empty($rows)) {
            $upsert($rows);
        }

        $this->command->info('Cities seeded: ' . count($cities) . ' records');
    }
}
