<?php

namespace App\Listeners;

use App\Events\InspectionPassed;
use App\Services\TrelloService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class MoveCardToPackingOnInspectionPassed implements ShouldQueue
{
    use InteractsWithQueue;

    public function __construct(
        protected TrelloService $trello,
    ) {}

    public function handle(InspectionPassed $event): void
    {
        $order = $event->order;

        if (!$order->trello_card_id) {
            Log::debug('No Trello card to move', ['order_uuid' => $order->uuid]);
            return;
        }

        try {
            // Move card to Packing list
            $success = $this->trello->moveCard($order->trello_card_id, 'packing');

            if ($success) {
                Log::info('Trello card moved to Packing', [
                    'order_uuid' => $order->uuid,
                    'card_id' => $order->trello_card_id,
                ]);
            } else {
                Log::warning('Failed to move Trello card to Packing', [
                    'order_uuid' => $order->uuid,
                    'card_id' => $order->trello_card_id,
                ]);
            }
        } catch (\Exception $e) {
            Log::error('Error moving Trello card to Packing', [
                'order_uuid' => $order->uuid,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
