<?php

namespace App\Console\Commands;

use App\Imports\SalaryTableImport;
use Illuminate\Console\Command;
use Maatwebsite\Excel\Facades\Excel;

class ImportSalaryTable extends Command
{
    protected $signature = 'salary:import
        {path : CSV/XLSX using the salary-table template}
        {--effective-from= : Default effective date for rows that omit one (default: today)}';

    protected $description = 'Bulk-import salary tables (structure/grade/step/amount) from the standard template.';

    public function handle(): int
    {
        $path = $this->argument('path');
        if (! is_file($path)) {
            $this->error("File not found: {$path}");

            return self::FAILURE;
        }

        $default = $this->option('effective-from') ?: now()->toDateString();
        $import = new SalaryTableImport($default);
        Excel::import($import, $path);

        $this->table(['Metric', 'Value'], [
            ['Created', $import->created],
            ['Updated', $import->updated],
            ['Skipped', $import->skipped],
        ]);
        foreach (array_slice($import->errors, 0, 20) as $e) {
            $this->line("  row {$e['row']}: ".implode('; ', $e['messages']));
        }

        return self::SUCCESS;
    }
}
