<?php

namespace App\Domain\POS\Listeners;

use App\Domain\POS\Events\POSTransactionCompleted;
use App\Domain\Notification\Services\NotificationService;
use App\Domain\Shared\Helpers\PublicLinkHelper;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class SendPOSReceiptNotification implements ShouldQueue
{
    public function __construct(
        private NotificationService $notificationService,
    ) {}

    public function handle(POSTransactionCompleted $event): void
    {
        try {
            $participant = $event->transaction->participant;

            if (!$participant) {
                return;
            }

            $this->notificationService->sendSimple(
                type: 'pos_transaction_completed',
                recipientId: $participant->id,
                recipientType: 'participant',
                data: [
                    'participant_name' => $participant->person?->full_name ?? '',
                    'transaction_number' => $event->transaction->receipt_number ?? $event->transaction->number ?? '',
                    'total_amount' => number_format(($event->transaction->total_amount ?? 0) / 100, 2),
                    'items_count' => (string) ($event->transaction->items_count ?? $event->transaction->items()->count()),
                    'receipt_link' => PublicLinkHelper::posReceiptLink($event->transaction),
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendPOSReceiptNotification failed: ' . $e->getMessage(), [
                'transaction_id' => $event->transaction->id,
            ]);
        }
    }

    public function failed(POSTransactionCompleted $event, \Throwable $exception): void
    {
        Log::critical('SendPOSReceiptNotification PERMANENTLY FAILED', [
            'transaction_id' => $event->transaction->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
