<?php

namespace App\Jobs;

use App\Models\Store;
use App\Services\WooCommerceService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class SyncOrdersJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
        $stores = Store::where('is_active', true)->get();
        
        foreach ($stores as $store) {
            try {
                $service = new WooCommerceService($store);
                $syncedCount = $service->syncOrders();
                
                Log::info("Synced {$syncedCount} orders from {$store->name}");
            } catch (\Exception $e) {
                Log::error("Failed to sync orders from {$store->name}", [
                    'error' => $e->getMessage()
                ]);
            }
        }
    }
}