<?php

namespace App\Console\Commands;

use App\Services\DealershipAdditionalFieldsRegistry;
use Illuminate\Console\Command;
use Mtc\MercuryDataModels\Dealership;

class MigrateDealershipDataToAttributes extends Command
{
    protected $signature = 'dealerships:migrate-data-to-attributes
                            {--dry-run : Report what would change without writing attribute values}';

    protected $description = 'Migrate integration-specific values from dealerships.data JSON into the polymorphic '
        . 'vehicle_attribute_values table. Run via `artisan tenants:run dealerships:migrate-data-to-attributes` '
        . 'for tenant context.';

    public function handle(DealershipAdditionalFieldsRegistry $registry): int
    {
        $this->line('Tenant: ' . tenant('id'));

        $slugs = $registry->slugs();
        if ($slugs->isEmpty()) {
            $this->line('  No registered dealership additional fields. Skipping.');
            return self::SUCCESS;
        }

        $dryRun = (bool) $this->option('dry-run');
        $migrated = 0;
        $skipped = 0;

        Dealership::query()
            ->with('attributeValues')
            ->eachById(function (Dealership $dealership) use ($registry, $slugs, $dryRun, &$migrated, &$skipped) {
                $rawData = $dealership->getRawOriginal('data');
                $data = is_string($rawData) ? (json_decode($rawData, true) ?: []) : (is_array($rawData) ? $rawData : []);

                foreach ($slugs as $slug) {
                    if (!array_key_exists($slug, $data)) {
                        continue;
                    }
                    $value = $data[$slug];
                    if ($value === null || $value === '') {
                        continue;
                    }
                    if ($dealership->attributeValues->firstWhere('slug', $slug) !== null) {
                        $skipped++;
                        continue;
                    }
                    if (!$dryRun) {
                        $registry->saveValue($dealership, $slug, $value);
                    }
                    $migrated++;
                }
            });

        $this->info(sprintf(
            '  Migrated: %d, Skipped (already present): %d%s',
            $migrated,
            $skipped,
            $dryRun ? ' (dry-run, no writes performed)' : ''
        ));

        return self::SUCCESS;
    }
}
