<?php

namespace App\Console\Commands;

use App\Services\Import\LegacyAmmarImportService;
use Illuminate\Console\Command;

class ImportLegacyAmmarData extends Command
{
    protected $signature = 'ammar:import-legacy
                            {--products : Import legacy products}
                            {--customers : Import legacy customers}
                            {--module-slug=ammar : Target ecommerce module slug}
                            {--store-id= : Target store id override}
                            {--zone-id= : Target zone id override}
                            {--chunk=100 : Chunk size for source records}
                            {--legacy-storage-path= : Absolute path to legacy storage/app/public}
                            {--skip-images : Import records without copying media files}
                            {--dry-run : Preview import without writing to database}';

    protected $description = 'Import products and customers from the legacy Ammar ecommerce database into the current system.';

    public function handle(LegacyAmmarImportService $service): int
    {
        $importProducts = (bool) $this->option('products');
        $importCustomers = (bool) $this->option('customers');

        if (!$importProducts && !$importCustomers) {
            $importProducts = true;
            $importCustomers = true;
        }

        $options = [
            'products' => $importProducts,
            'customers' => $importCustomers,
            'module_slug' => (string) $this->option('module-slug'),
            'store_id' => $this->option('store-id') ? (int) $this->option('store-id') : null,
            'zone_id' => $this->option('zone-id') ? (int) $this->option('zone-id') : null,
            'chunk' => max(1, (int) $this->option('chunk')),
            'legacy_storage_path' => $this->option('legacy-storage-path') ? (string) $this->option('legacy-storage-path') : null,
            'skip_images' => (bool) $this->option('skip-images'),
            'dry_run' => (bool) $this->option('dry-run'),
        ];

        try {
            $summary = $service->import($this, $options);
        } catch (\Throwable $exception) {
            $this->error($exception->getMessage());
            return self::FAILURE;
        }

        $this->newLine();
        $this->info('Legacy import finished.');
        foreach ($summary as $key => $value) {
            $this->line(sprintf('%s: %s', $key, $value));
        }

        return self::SUCCESS;
    }
}
