<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('aircraft', function (Blueprint $table) {
            $table->id();
            $table->string('designator');
            $table->string('manufacturer_code');
            $table->string('model_full_name');
            $table->string('aircraft_description');
            $table->string('engine_type');
            $table->unsignedTinyInteger('engine_count');
            $table->string('wtc');
            $table->timestamps();
        });

        $this->importCsv();
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('aircraft');
    }

    /**
     * Import aircraft data from CSV file.
     */
    private function importCsv(): void
    {
        $path = storage_path('app/private/seed_data/aircraft.csv');

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

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

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

        // Skip the header row
        fgetcsv($handle);

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

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

            [$designator, $manufacturerCode, $modelFullName, $aircraftDescription, $engineType, $engineCount, $wtc] = $row;

            $batch[] = [
                'designator'           => trim($designator),
                'manufacturer_code'    => trim($manufacturerCode),
                'model_full_name'      => trim($modelFullName),
                'aircraft_description' => trim($aircraftDescription),
                'engine_type'          => trim($engineType),
                'engine_count'         => (int) trim($engineCount),
                'wtc'                  => trim(str_replace(["\r", "\n"], '', $wtc)),
                'created_at'           => $now,
                'updated_at'           => $now,
            ];

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

        fclose($handle);

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