<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class FixImportMappingEntities extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:fix-mapping-entities {--dry-run : Show changes without applying them}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix entity names in import_mappings table to use canonical roots';

    /**
     * Entity name mappings from incorrect to correct canonical roots
     */
    protected array $entityMapping = [
        'contracts' => 'contract',
        'contract' => 'contract',
        'client_cases' => 'client_case',
        'client_case' => 'client_case',
        'person_addresses' => 'address',
        'addresses' => 'address',
        'address' => 'address',
        'person_phones' => 'phone',
        'phones' => 'phone',
        'phone' => 'phone',
        'emails' => 'email',
        'email' => 'email',
        'activities' => 'activity',
        'activity' => 'activity',
        'persons' => 'person',
        'person' => 'person',
        'accounts' => 'account',
        'account' => 'account',
        'payments' => 'payment',
        'payment' => 'payment',
        'bookings' => 'booking',
        'booking' => 'booking',
    ];

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $dryRun = $this->option('dry-run');

        if ($dryRun) {
            $this->info('Running in DRY-RUN mode - no changes will be made');
        }

        $mappings = DB::table('import_mappings')
            ->whereNotNull('entity')
            ->where('entity', '!=', '')
            ->get();

        if ($mappings->isEmpty()) {
            $this->info('No mappings found to fix.');
            return 0;
        }

        $this->info("Found {$mappings->count()} mappings to check");
        $this->newLine();

        $updates = [];
        $unchanged = 0;

        foreach ($mappings as $mapping) {
            $currentEntity = trim($mapping->entity);
            
            if (isset($this->entityMapping[$currentEntity])) {
                $correctEntity = $this->entityMapping[$currentEntity];
                
                if ($currentEntity !== $correctEntity) {
                    $updates[] = [
                        'id' => $mapping->id,
                        'current' => $currentEntity,
                        'correct' => $correctEntity,
                        'source' => $mapping->source_column,
                        'target' => $mapping->target_field,
                    ];
                } else {
                    $unchanged++;
                }
            } else {
                $this->warn("Unknown entity type: {$currentEntity} (ID: {$mapping->id})");
            }
        }

        if (empty($updates)) {
            $this->info("✓ All {$unchanged} mappings already have correct entity names!");
            return 0;
        }

        // Display changes
        $this->info("Changes to be made:");
        $this->newLine();

        $table = [];
        foreach ($updates as $update) {
            $table[] = [
                $update['id'],
                $update['source'],
                $update['target'],
                $update['current'],
                $update['correct'],
            ];
        }

        $this->table(
            ['ID', 'Source Column', 'Target Field', 'Current Entity', 'Correct Entity'],
            $table
        );

        $this->newLine();
        $this->info("Total changes: " . count($updates));
        $this->info("Unchanged: {$unchanged}");

        if ($dryRun) {
            $this->newLine();
            $this->warn('DRY-RUN mode: No changes were made. Run without --dry-run to apply changes.');
            return 0;
        }

        // Confirm before proceeding
        if (!$this->confirm('Do you want to apply these changes?', true)) {
            $this->info('Operation cancelled.');
            return 0;
        }

        // Apply updates
        $updated = 0;
        foreach ($updates as $update) {
            DB::table('import_mappings')
                ->where('id', $update['id'])
                ->update(['entity' => $update['correct']]);
            $updated++;
        }

        $this->newLine();
        $this->info("✓ Successfully updated {$updated} mappings!");
        
        return 0;
    }
}
