<?php

namespace Modules\MedRegistry\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Modules\MedRegistry\Support\CatalogSync;

/**
 * Re-runs the catalog sync (same logic as MedregCatalogSeeder). Scheduled
 * weekly by MedRegistryServiceProvider so new/removed modules are picked up
 * without manual reseeding.
 */
class SyncCatalogCommand extends Command
{
    protected $signature = 'medreg:sync-catalog';

    protected $description = 'Sync the MedRegistry module catalog from Modules/*/module.json manifests (extra.medical block + curated retro-fit map)';

    public function handle(): int
    {
        if (! Schema::hasTable('medreg_modules')) {
            $this->warn('medreg_modules table missing — install the MedRegistry module first (/med-registry/install).');

            return 1;
        }

        $summary = (new CatalogSync())->sync();

        $this->info(sprintf(
            'Catalog synced: %d modules present, %d marked absent.',
            $summary['synced'],
            $summary['marked_absent']
        ));

        return 0;
    }
}
