<?php

namespace App\Console\Commands;

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

class PopulateImportMappingEntities extends Command
{
    protected $signature = 'import:populate-mapping-entities {--dry-run : Show changes without applying them}';

    protected $description = 'Populate entity column from target_field for mappings where entity is null';

    protected array $entityMap = [
        'contracts' => 'contract',
        'client_cases' => 'client_case',
        'person_addresses' => 'address',
        'person_phones' => 'phone',
        'emails' => 'email',
        'activities' => 'activity',
        'payments' => 'payment',
        'accounts' => 'account',
        'persons' => 'person',
        'person' => 'person',
        'contract' => 'contract',
        'client_case' => 'client_case',
        'address' => 'address',
        'phone' => 'phone',
        'email' => 'email',
        'activity' => 'activity',
        'payment' => 'payment',
        'account' => 'account',
    ];

    public function handle()
    {
        $dryRun = $this->option('dry-run');

        $this->info('Populating entity column from target_field...');
        if ($dryRun) {
            $this->warn('DRY RUN MODE - No changes will be made');
        }

        // Get all mappings where entity is null
        $mappings = DB::table('import_mappings')
            ->whereNull('entity')
            ->get();

        if ($mappings->isEmpty()) {
            $this->info('No mappings found with null entity.');
            return 0;
        }

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

        $updated = 0;
        $skipped = 0;

        foreach ($mappings as $mapping) {
            $targetField = $mapping->target_field;
            
            // Parse the target_field to extract entity and field
            if (str_contains($targetField, '.')) {
                [$rawEntity, $field] = explode('.', $targetField, 2);
            } elseif (str_contains($targetField, '->')) {
                [$rawEntity, $field] = explode('->', $targetField, 2);
            } else {
                $this->warn("Skipping mapping ID {$mapping->id}: Cannot parse target_field '{$targetField}'");
                $skipped++;
                continue;
            }

            $rawEntity = trim($rawEntity);
            $field = trim($field);

            // Map to canonical entity name
            $canonicalEntity = $this->entityMap[$rawEntity] ?? $rawEntity;

            $this->line(sprintf(
                "ID %d: '%s' -> '%s' => entity='%s', field='%s'",
                $mapping->id,
                $mapping->source_column,
                $targetField,
                $canonicalEntity,
                $field
            ));

            if (!$dryRun) {
                DB::table('import_mappings')
                    ->where('id', $mapping->id)
                    ->update([
                        'entity' => $canonicalEntity,
                        'target_field' => $field,
                    ]);
                $updated++;
            }
        }

        $this->newLine();
        if ($dryRun) {
            $this->info("Dry run complete. Would have updated {$mappings->count()} mappings.");
        } else {
            $this->info("Successfully updated {$updated} mappings.");
        }

        if ($skipped > 0) {
            $this->warn("Skipped {$skipped} mappings that couldn't be parsed.");
        }

        return 0;
    }
}
