<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class AirlinesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $path = storage_path('app/private/seed_data/Airlines.csv');
        $file = fopen($path, 'r');

        $header = fgetcsv($file, separator: ';');

        $keep = ['codeIataAirline', 'codeIcaoAirline', 'nameAirline', 'codeIso2Country', 'nameCountry', 'slug', 'statusAirline'];

        $renames = [
            'airlineId' => 'id',
            'codeIataAirline' => 'IATA_code',
            'codeIcaoAirline' => 'icao_code',
            'slug' => 'internal_name',
            'nameAirline'     => 'name',
            'codeIso2Country' => 'country_code',
            'nameCountry'     => 'country_name',
            'statusAirline'  => 'active'
        ];

        while (($row = fgetcsv($file, separator: ';')) !== false) {
            $data = array_combine($header, $row);
            $filtered = array_intersect_key($data, array_flip($keep));

            foreach ($renames as $old => $new) {
                if (array_key_exists($old, $filtered)) {
                    $filtered[$new] = $filtered[$old];
                    unset($filtered[$old]);
                }
            }
            $filtered['active'] = $filtered['active'] === 'active';
            $filtered['logo'] = $filtered['IATA_code'] ? $filtered['IATA_code'].'.png' : null;
            DB::table('airlines')->insert($filtered);
        }

        fclose($file);
    }
}
