<?php

namespace Modules\ProductCompat\Console;

use App\Product;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Modules\ProductCompat\Entities\PcPartNumber;

/**
 * Export a batch of products to a JSON file for OFFLINE enrichment (e.g. hand it
 * to an AI assistant that fills part numbers / compatibility / description in
 * bulk, with no online rate limits) and re-import with productcompat:import-enrichment.
 *
 *   php artisan productcompat:export-products --limit=200 --missing --out=storage/app/pc_batch.json
 *
 * The JSON is an array of { id, sku, name, brand, category, existing:{...} }.
 */
class ExportProducts extends Command
{
    protected $signature = 'productcompat:export-products
        {--business= : Business id (default: all)}
        {--limit=200 : Max products to export}
        {--offset=0 : Skip this many (paging through the catalog)}
        {--missing : Only products missing a part number, description or image}
        {--out= : Output file path (default: storage/app/productcompat/export_<n>.json)}';

    protected $description = 'Export products to JSON for offline bulk enrichment.';

    public function handle(): int
    {
        $limit  = max(1, (int) $this->option('limit'));
        $offset = max(0, (int) $this->option('offset'));

        // Full rows (custom fields + category needed by ProductContext).
        $q = Product::query();
        if ($b = $this->option('business')) {
            $q->where('business_id', (int) $b);
        }
        if ($this->option('missing')) {
            $q->where(function ($w) {
                $w->whereNotExists(fn ($s) => $s->select(DB::raw(1))->from('pc_part_numbers')
                        ->whereColumn('pc_part_numbers.product_id', 'products.id'))
                    ->orWhereNull('product_description')->orWhere('product_description', '')
                    ->orWhereNull('image')->orWhere('image', '');
            });
        }

        $rows = $q->orderBy('id')->offset($offset)->limit($limit)->get();
        if ($rows->isEmpty()) {
            $this->info('No products matched.');
            return self::SUCCESS;
        }

        $out = [];
        foreach ($rows as $p) {
            $ctx = \Modules\ProductCompat\Entities\Services\ProductContext::gather($p);
            $out[] = [
                'id'            => (int) $p->id,
                'sku'           => $ctx['sku'],
                'name'          => $ctx['name'],
                'brand'         => $ctx['brand'],
                'category'      => trim($ctx['category'] . ' / ' . $ctx['sub_category'], ' /'),
                'description'   => $ctx['description'],
                'custom_fields' => $ctx['custom_fields'],
                'existing_identifiers' => $ctx['existing_identifiers'],
                'has_image'     => ! empty($p->image),
            ];
        }

        $path = $this->option('out') ?: storage_path('app/productcompat/export_' . $offset . '_' . $limit . '.json');
        if (! is_dir(dirname($path))) {
            @mkdir(dirname($path), 0755, true);
        }
        file_put_contents($path, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));

        $this->info('Exported ' . count($out) . ' product(s) → ' . $path);
        $this->line('Enrich it offline, then: php artisan productcompat:import-enrichment ' . $path);

        return self::SUCCESS;
    }
}
