<?php

namespace App\Console\Commands\Utils;

use Illuminate\Console\Command;
use App\Services\LocalizationService;
use Illuminate\Support\Facades\File;

class ImportCities extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'utils:import-cities';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import cities from a JSON file';

    /**
     * Execute the console command.
     */
    public function handle(LocalizationService $localizationService)
    {
        $jsonFolderPath = base_path('json');
        $files = File::files($jsonFolderPath);

        $jsonFiles = array_filter($files, function ($file) {
            return $file->getExtension() === 'ndjson';
        });

        if (empty($jsonFiles)) {
            $this->error('No ND JSON files found in the json folder.');
            return 1;
        }

        $fileOptions = array_map(function ($file) {
            return $file->getFilename();
        }, $jsonFiles);

        $filePath = $this->choice('Please select a ND JSON file', $fileOptions);

        $cityType = $this->choice('Please select the city type', ['city', 'town', 'village']);

        $fullFilePath = $jsonFolderPath . DIRECTORY_SEPARATOR . $filePath;

        if (!file_exists($fullFilePath) || !is_readable($fullFilePath)) {
            $this->error('The file does not exist or is not readable.');
            return 1;
        }

        $citiesData = [];
        $fileHandle = fopen($fullFilePath, 'r');
        if ($fileHandle) {
            while (($line = fgets($fileHandle)) !== false) {
                $cityData = json_decode($line, true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $this->error('Invalid NDJSON file.');
                    fclose($fileHandle);
                    return 1;
                }
                $citiesData[] = $cityData;
            }
            fclose($fileHandle);
        } else {
            $this->error('Unable to open the file.');
            return 1;
        }

        $localizationService->importCities($citiesData, $cityType);

        $this->info('Cities imported successfully.');
        return 0;
    }
}
