<?php

namespace App\Console\Commands;

use App\Jobs\ProcessLargeImportJob;
use App\Models\Import;
use App\Services\Import\ImportServiceV2;
use Illuminate\Console\Command;

class TestImportV2Command extends Command
{
    protected $signature = 'import:test-v2 {import_id : The import ID to process} {--queue : Process via queue}';

    protected $description = 'Test ImportServiceV2 with an existing import';

    public function handle()
    {
        $importId = $this->argument('import_id');
        $useQueue = $this->option('queue');

        $import = Import::find($importId);

        if (! $import) {
            $this->error("Import {$importId} not found.");

            return 1;
        }

        $this->info("Processing import: {$import->id} ({$import->file_name})");
        $this->info("Source: {$import->source_type}");
        $this->info("Status: {$import->status}");
        $this->newLine();

        if ($useQueue) {
            $this->info('Dispatching to queue...');
            ProcessLargeImportJob::dispatch($import, auth()->id());
            $this->info('Job dispatched successfully. Monitor queue for progress.');

            return 0;
        }

        $this->info('Processing synchronously...');
        $service = app(ImportServiceV2::class);

        try {
            $results = $service->process($import, auth()->user());

            $this->newLine();
            $this->info('Processing completed!');
            $this->table(
                ['Metric', 'Count'],
                [
                    ['Total rows', $results['total']],
                    ['Imported', $results['imported']],
                    ['Skipped', $results['skipped']],
                    ['Invalid', $results['invalid']],
                ]
            );

            return 0;
        } catch (\Throwable $e) {
            $this->error('Processing failed: '.$e->getMessage());
            $this->error($e->getTraceAsString());

            return 1;
        }
    }
}
