<?php

namespace App\Console\Commands;

use App\Imports\AutoGrabToVehicleImport;
use Illuminate\Console\Command;
use Mtc\MercuryDataModels\Vehicle;

use function tenant;

/**
 * One-off repair for AutoGrab vehicles suppressed by an unreadable registration plate.
 *
 * Cherished / prefix-format plates (e.g. Y31NAB) defeat the plate-based registration date
 * finder, and mapDataToColumns() force-unpublishes any vehicle without a first_registration_date
 * on every sync. AutoGrabToVehicleImport now falls back to the feed's manufacture year, which
 * fixes future syncs but never republishes stock already suppressed: update() keeps the existing
 * is_published value once the forced unpublish stops firing.
 *
 * This command backfills first_registration_date (plate first, then the year captured in the
 * vehicle's stored feed payload) for active unpublished AutoGrab vehicles that lack one, and
 * republishes them unless a do-not-publish import condition still applies. Vehicles with no
 * derivable date are left untouched.
 */
class AutoGrabRepublishMissingRegDate extends Command
{
    protected $signature = 'autograb:republish-missing-reg-date
        {--dry-run : Report what would change without saving}';

    protected $description = 'Backfill registration dates and republish AutoGrab vehicles hidden by unreadable plates';

    public function handle(): int
    {
        $dryRun = (bool) $this->option('dry-run');
        $import = new AutoGrabToVehicleImport();

        $republished = 0;
        $held = 0;
        $noDate = 0;

        Vehicle::query()
            ->where('stock_provider', $import->getProviderName())
            ->where('is_published', false)
            ->whereNull('first_registration_date')
            ->chunkById(200, function ($vehicles) use ($import, $dryRun, &$republished, &$held, &$noDate) {
                foreach ($vehicles as $vehicle) {
                    $date = $import->getRegistrationDateFromRegistrationNumber($vehicle->registration_number)
                        ?? $import->registrationDateFromYear($vehicle->data ?? []);

                    if ($date === null) {
                        $noDate++;
                        continue;
                    }

                    $vehicle->first_registration_date = $date;
                    $vehicle->is_published = $import->shouldBePublished(
                        fn () => true,
                        $import->getProviderName(),
                        $vehicle
                    );

                    $vehicle->is_published ? $republished++ : $held++;

                    if ($dryRun) {
                        $this->line(sprintf(
                            '  would set %s (%s) first_registration_date=%s is_published=%s',
                            $vehicle->id,
                            $vehicle->registration_number,
                            $date,
                            $vehicle->is_published ? 'true' : 'false'
                        ));
                        continue;
                    }

                    $vehicle->save();
                }
            });

        $this->info(sprintf(
            '%s[%s] republished: %d, dated but held by publish conditions: %d, no derivable date (skipped): %d',
            $dryRun ? '[dry-run] ' : '',
            tenant('id') ?? 'central',
            $republished,
            $held,
            $noDate
        ));

        return self::SUCCESS;
    }
}
