<?php

namespace App\Listeners;

use App\Events\ReadyToShipIntent;
use App\Services\CourierService;
use App\Events\ShipmentCreated;
use App\Events\ShipmentCreationFailed;
use Illuminate\Support\Facades\Log;

class CreateShipmentOnReadyToShip
{
    /**
     * Create the event listener.
     */
    public function __construct(protected CourierService $courierService)
    {
    }

    /**
     * Handle the event - create shipment when Trello card moves to Ready to Ship.
     */
    public function handle(ReadyToShipIntent $event): void
    {
        $order = $event->order;

        Log::info('Creating shipment from Ready to Ship intent', [
            'order_uuid' => $order->uuid,
        ]);

        try {
            $result = $this->courierService->createShipmentForOrder($order);

            // Emit event to trigger Slack/Trello updates
            ShipmentCreated::dispatch(
                $order,
                $result['waybill_id'],
                $result['tracking_number'],
                $result['sticker_path'],
                $result['waybill_path'],
            );
        } catch (\Exception $e) {
            Log::error('Failed to create shipment from Ready to Ship intent', [
                'order_uuid' => $order->uuid,
                'error' => $e->getMessage(),
            ]);

            // Emit failure event
            ShipmentCreationFailed::dispatch($order, $e->getMessage());
        }
    }
}
