<?php

namespace App\Console\Commands;

use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('badhonsworld:auto-import')]
#[Description('Automatically import new products from badhonsworld.com into the fallback category')]
class BadhonsworldAutoImportCommand extends Command
{
    /**
     * Execute the console command.
     */
    public function handle(\App\Services\BadhonsworldService $service)
    {
        $this->info('Starting automatic daily import of new products from badhonsworld.com...');
        
        try {
            // Find or create default fallback category
            $fallbackCategory = \App\Models\Category::firstOrCreate(
                ['slug' => 'general'],
                ['name' => 'General']
            );

            $importedCount = $service->bulkImportAll($fallbackCategory->id, function ($count) {
                $this->info("Imported {$count} products so far...");
            });

            $this->info("Successfully finished daily auto-import! Imported/updated a total of {$importedCount} products.");
        } catch (\Exception $e) {
            $this->error('An error occurred during automatic import: ' . $e->getMessage());
            return Command::FAILURE;
        }

        return Command::SUCCESS;
    }
}
