<?php

namespace App\Jobs;

use App\Models\BlingSyncState;
use App\Models\IntegrationLog;
use App\Services\BlingClient;
use App\Services\VetorClient;

class ImportOrdersJob
{
    public function handle(BlingClient $bling, VetorClient $vetor): void
    {
        $state = BlingSyncState::query()->first() ?: BlingSyncState::create(['last_order_id' => null]);

        $lastId = $state->last_order_id;

        // 1) Buscar pedidos faturados no Bling após $lastId (ajustar endpoint real)
        // Exemplo fictício: $orders = $bling->apiRequest('GET', 'pedidos?status=faturado&after_id=' . (int) $lastId);
        $orders = [];

        // 2) Enviar ao Vetor e atualizar marcador de sincronização
        foreach ($orders as $order) {
            $vetor->postOrder($order);
            $lastId = max((int) $lastId, (int) ($order['id'] ?? 0));
        }

        if ($lastId !== $state->last_order_id) {
            $state->last_order_id = $lastId;
            $state->save();
        }

        IntegrationLog::write('import_orders_executed', [
            'imported' => is_countable($orders) ? count($orders) : null,
            'last_order_id' => $state->last_order_id,
        ]);
    }
}
