<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->id();
            $table->string('code', 2)->unique();
            $table->string('name');
            $table->string('continent', 2);
            $table->timestamps();
        });

        $this->importCsv();
    }

    public function down(): void
    {
        Schema::dropIfExists('countries');
    }

    private function importCsv(): void
    {
        $path = storage_path('app/private/seed_data/countries.csv');

        if (! file_exists($path)) {
            throw new \RuntimeException("Countries CSV not found at: {$path}");
        }

        $handle = fopen($path, 'rb');

        if ($handle === false) {
            throw new \RuntimeException("Failed to open countries CSV at: {$path}");
        }

        // Skip header row
        fgetcsv($handle);

        $batch = [];
        $batchSize = 500;
        $now = now()->toDateTimeString();

        while (($row = fgetcsv($handle)) !== false) {
            if (count($row) < 4) {
                continue;
            }

            // id, code, name, continent, wikipedia_link, keywords
            [, $code, $name, $continent] = $row;

            $batch[] = [
                'code'       => trim($code),
                'name'       => trim($name),
                'continent'  => trim($continent),
                'created_at' => $now,
                'updated_at' => $now,
            ];

            if (count($batch) >= $batchSize) {
                DB::table('countries')->insert($batch);
                $batch = [];
            }
        }

        fclose($handle);

        if (! empty($batch)) {
            DB::table('countries')->insert($batch);
        }
    }
};
