<?php

namespace App\Listeners;

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

class NotifySlackOnOrderCreated
{
    public function __construct(
        protected SlackNotifierService $slack,
        protected TrelloService $trello,
        protected QrStickerService $qrSticker,
    ) {
    }

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

        // Extract design name from first order item's product
        $designName = $order->items->first()?->product?->name ?? '—';
        $printStock = $order->items->first()?->printStock?->name ?? '—';

        // Calculate print size from first item's dimensions
        $printSize = '—';
        $firstItem = $order->items->first();
        if ($firstItem) {
            if ($firstItem->type === 'wallpaper' && $firstItem->length) {
                $printSize = $firstItem->length . 'm';
            } elseif ($firstItem->type === 'mural' && $firstItem->width && $firstItem->height) {
                $printSize = $firstItem->width . 'm × ' . $firstItem->height . 'm';
            }
        }

        // Build detailed Slack message
        $message = "🆕 New {$event->orderType} order: Order #{$order->order_number}\n" .
            "Design: '{$designName}'\n" .
            "Size: {$printSize}";

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

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

        // Create Trello card
        $cardId = $this->trello->createCard(
            $order->uuid,
            $order->order_number,
            $event->orderType,
        );

        if ($cardId) {
            $order->update(['trello_card_id' => $cardId]);

            // Populate custom fields with the same info
            $this->trello->setTextField($cardId, 'order_id', $order->uuid);
            $this->trello->setTextField($cardId, 'design_name', $designName);
            $this->trello->setTextField($cardId, 'print_stock', $printStock);
            $this->trello->setTextField($cardId, 'customer_name', $order->customer_name ?? '—');
            $this->trello->setTextField($cardId, 'print_size', $printSize);

            Log::info('Trello card created for order', ['order_uuid' => $order->uuid, 'card_id' => $cardId]);

            // Generate QR sticker and attach to Trello card
            try {
                $stickerPaths = $this->qrSticker->generateSticker($order);
                $pdfPath = storage_path('app/public/' . $stickerPaths['pdf_path']);

                if (Storage::disk('public')->exists($stickerPaths['pdf_path'])) {
                    // Generate a public URL for the PDF
                    $stickerUrl = Storage::disk('public')->url($stickerPaths['pdf_path']);

                    // Attach to Trello card
                    $this->trello->attachFile(
                        $cardId,
                        "QR-Sticker-{$order->order_number}.pdf",
                        $stickerUrl
                    );

                    Log::info('QR sticker attached to Trello card', [
                        'order_uuid' => $order->uuid,
                        'card_id' => $cardId,
                        'pdf_path' => $stickerPaths['pdf_path'],
                    ]);
                }
            } catch (\Exception $e) {
                Log::error('Failed to generate or attach QR sticker to Trello', [
                    'order_uuid' => $order->uuid,
                    'error' => $e->getMessage(),
                ]);
            }
        }
    }
}
