<?php

namespace Modules\ProductCompat\Console;

use Illuminate\Console\Command;
use Modules\ProductCompat\Entities\Services\CoverageReport;

/**
 * Report how much of the catalogue has been parsed / enriched, so you can
 * confirm every product with custom-field data has been processed.
 *
 *   php artisan productcompat:coverage --business=1
 */
class Coverage extends Command
{
    protected $signature = 'productcompat:coverage
        {--business= : Limit to one business id}
        {--unparsed-skus=0 : Also list up to N SKUs still needing a parse}';

    protected $description = 'Show parse / enrichment coverage across the catalogue.';

    public function handle(): int
    {
        $biz = $this->option('business') ? (int) $this->option('business') : null;
        $c = CoverageReport::gather($biz);

        $this->info('ProductCompat coverage' . ($biz ? " (business #{$biz})" : ' (all businesses)'));
        $this->table(['Metric', 'Count'], [
            ['Total products', number_format($c['total'])],
            ['Parseable (have custom-field data)', number_format($c['parseable'])],
            ['  -> parsed', number_format($c['parsed'])],
            ['  -> NOT parsed yet', number_format($c['unparsed'])],
            ['Products with >=1 part number', number_format($c['with_parts'])],
            ['Queue: queued', number_format($c['queue']['queued'])],
            ['Queue: done', number_format($c['queue']['done'])],
            ['Queue: failed', number_format($c['queue']['failed'])],
        ]);

        if ($c['unparsed'] === 0) {
            $this->info('All products with custom-field data have been parsed.');
        } else {
            $this->warn("{$c['unparsed']} product(s) with custom-field data still need parsing - run productcompat:parse-custom-fields.");
            $n = (int) $this->option('unparsed-skus');
            if ($n > 0) {
                $this->line('First unparsed SKUs: ' . implode(', ', CoverageReport::unparsedSkus($biz, $n)));
            }
        }

        return self::SUCCESS;
    }
}
