<?php

namespace App\Console\Commands;

use App\Services\MasterlistImporter;
use Illuminate\Console\Command;

class ImportMasterlist extends Command
{
    protected $signature = 'import:masterlist {file} {--sheet=0}';
    protected $description = 'Import the worker masterlist Excel (first sheet) into the database';

    public function handle(MasterlistImporter $importer): int
    {
        $file = $this->argument('file');

        if (! is_file($file)) {
            $this->error("File not found: {$file}");

            return self::FAILURE;
        }

        $this->info('Loading spreadsheet…');
        $result = $importer->import($file, (int) $this->option('sheet'));

        $this->newLine();
        $this->info("Created: {$result['created']}  Updated: {$result['updated']}  Skipped(no name): {$result['skipped']}");
        $this->line("Sites: {$result['sites']}  Nationalities: {$result['nationalities']}  Banks: {$result['banks']}");

        if ($result['issues']) {
            $this->warn(count($result['issues']).' rows flagged for review:');
            foreach (array_slice($result['issues'], 0, 15) as $i) {
                $this->line('  - '.$i);
            }
            if (count($result['issues']) > 15) {
                $this->line('  … and '.(count($result['issues']) - 15).' more.');
            }
        }

        return self::SUCCESS;
    }
}
