<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\CashSessionClosed;
use App\Domain\Notification\Services\NotificationService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

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

    public function handle(CashSessionClosed $event): void
    {
        try {
            $this->notificationService->sendToRole(
                type: 'cash_session_closed',
                role: 'academy_admin',
                data: [
                    'cashier_name' => $event->actor->name,
                    'session_date' => $event->cashSession->opened_at?->format('Y-m-d') ?? now()->format('Y-m-d'),
                    'total_sales' => number_format(($event->cashSession->total_sales ?? 0) / 100, 2),
                    'transactions_count' => (string) ($event->cashSession->transactions_count ?? 0),
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendCashSessionClosedNotification failed: ' . $e->getMessage(), [
                'cash_session_id' => $event->cashSession->id,
            ]);
        }
    }

    public function failed(CashSessionClosed $event, \Throwable $exception): void
    {
        Log::critical('SendCashSessionClosedNotification PERMANENTLY FAILED', [
            'cash_session_id' => $event->cashSession->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
