<?php

namespace App\Console\Commands;

use App\Models\Import;
use App\Services\Import\ImportSimulationServiceV2;
use Illuminate\Console\Command;

class SimulateImportV2Command extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:simulate-v2 {import_id} {--limit=100 : Number of rows to simulate} {--verbose : Include detailed information}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Simulate ImportServiceV2 without persisting data';

    /**
     * Execute the console command.
     */
    public function handle(ImportSimulationServiceV2 $service): int
    {
        $importId = $this->argument('import_id');
        $limit = (int) $this->option('limit');
        $verbose = (bool) $this->option('verbose');

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

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

            return 1;
        }

        $this->info("Simulating import #{$importId} - {$import->file_name}");
        $this->info("Client: ".($import->client->name ?? 'N/A'));
        $this->info("Limit: {$limit} rows");
        $this->line('');

        $result = $service->simulate($import, $limit, $verbose);

        if (! $result['success']) {
            $this->error('Simulation failed: '.$result['error']);

            return 1;
        }

        $this->info("✓ Simulated {$result['total_simulated']} rows");
        $this->line('');

        // Display summaries
        if (! empty($result['summaries'])) {
            $this->info('=== Entity Summaries ===');
            $summaryRows = [];

            foreach ($result['summaries'] as $entity => $stats) {
                $summaryRows[] = [
                    'entity' => $entity,
                    'create' => $stats['create'],
                    'update' => $stats['update'],
                    'skip' => $stats['skip'],
                    'invalid' => $stats['invalid'],
                    'total' => array_sum($stats),
                ];
            }

            $this->table(
                ['Entity', 'Create', 'Update', 'Skip', 'Invalid', 'Total'],
                $summaryRows
            );
            $this->line('');
        }

        // Display row previews (first 5)
        if (! empty($result['rows'])) {
            $this->info('=== Row Previews (first 5) ===');

            foreach (array_slice($result['rows'], 0, 5) as $row) {
                $this->line("Row #{$row['row_number']}:");

                if (! empty($row['entities'])) {
                    foreach ($row['entities'] as $entity => $data) {
                        $action = $data['action'];
                        $color = match ($action) {
                            'create' => 'green',
                            'update' => 'yellow',
                            'skip' => 'gray',
                            'invalid', 'error' => 'red',
                            default => 'white',
                        };

                        $line = "  {$entity}: <fg={$color}>{$action}</>";

                        if (isset($data['reference'])) {
                            $line .= " ({$data['reference']})";
                        }

                        if (isset($data['existing_id'])) {
                            $line .= " [ID: {$data['existing_id']}]";
                        }

                        $this->line($line);

                        if ($verbose && ! empty($data['changes'])) {
                            foreach ($data['changes'] as $field => $change) {
                                $this->line("    {$field}: {$change['old']} → {$change['new']}");
                            }
                        }

                        if (! empty($data['errors'])) {
                            foreach ($data['errors'] as $error) {
                                $this->error("    ✗ {$error}");
                            }
                        }
                    }
                }

                if (! empty($row['warnings'])) {
                    foreach ($row['warnings'] as $warning) {
                        $this->warn("  ⚠ {$warning}");
                    }
                }

                if (! empty($row['errors'])) {
                    foreach ($row['errors'] as $error) {
                        $this->error("  ✗ {$error}");
                    }
                }

                $this->line('');
            }
        }

        $this->info('Simulation completed successfully.');

        return 0;
    }
}
