<?php

namespace App\Listeners;

use App\Events\ShipmentCreated;
use App\Services\SlackNotifierService;
use App\Services\TrelloService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class NotifySlackOnShipmentCreated
{
    public function __construct(
        protected SlackNotifierService $slack,
        protected TrelloService $trello,
    ) {
    }

    public function handle(ShipmentCreated $event): void
    {
        $order = $event->order;
        $message = "📦 Shipment created: Order #{$order->order_number}\n" .
            "Waybill: {$event->waybillId}\n" .
            "Tracking: {$event->trackingNumber}";

        // Notify Slack #shipping
        $this->slack->shipping($message);

        Log::info('Shipment created notification sent', ['order_uuid' => $order->uuid]);

        // Attach shipping documents to Trello card
        if ($order->trello_card_id) {
            if ($event->stickerPath && Storage::disk('public')->exists($event->stickerPath)) {
                $stickerUrl = Storage::disk('public')->url($event->stickerPath);
                $this->trello->attachFile($order->trello_card_id, 'Sticker.pdf', $stickerUrl);
            }

            if ($event->waybillPath && Storage::disk('public')->exists($event->waybillPath)) {
                $waybillUrl = Storage::disk('public')->url($event->waybillPath);
                $this->trello->attachFile($order->trello_card_id, 'Waybill.pdf', $waybillUrl);
            }

            // Move card to Awaiting Collection
            $this->trello->moveCard($order->trello_card_id, 'Awaiting Collection');

            Log::info('Trello card updated with shipment details', ['order_uuid' => $order->uuid]);
        }
    }
}
