<?php

namespace Modules\Booking\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Modules\Booking\Events\DriverAssigned;
use Modules\Shared\Sms\SmsService;

/**
 * Notifies the passenger of their driver/car details whenever a driver is
 * assigned or reassigned (domain.md — driver/vehicle assignment). Queued
 * since it's an outbound HTTP call to the SMS gateway.
 */
class SendDriverAssignedSms implements ShouldQueue
{
    public function __construct(private readonly SmsService $smsService) {}

    public function handle(DriverAssigned $event): void
    {
        $booking = $event->booking;

        $this->smsService->send($booking->passenger_phone, $this->message($event));
    }

    private function message(DriverAssigned $event): string
    {
        $booking = $event->booking;

        $vehicle = trim($booking->car_model !== null
            ? "{$booking->car_plate_number} ({$booking->car_model})"
            : $booking->car_plate_number);
        $route = $booking->route->fromDestination->name.' - '.$booking->route->toDestination->name;
        $mmRoute = $booking->route->fromDestination->mm_name.' - '.$booking->route->toDestination->mm_name;

        $appName = 'BNF Express - '.config('app.name');
        $supportPhone = config('app.support_phone');
        $supportEmail = config('app.support_email');
        $contact = "Help: {$supportPhone} / {$supportEmail}\nအကူအညီလိုအပ်ပါက ဆက်သွယ်ရန်: {$supportPhone} / {$supportEmail}";

        if ($event->isFirstAssignment) {
            $en = "Your driver has been assigned for booking {$booking->booking_ref} ({$route}). Driver: {$booking->driver_name}, {$booking->driver_phone}. Vehicle: {$vehicle}.";
            $mm = "ဘွတ်ကင် {$booking->booking_ref} ({$mmRoute}) အတွက် ယာဉ်မောင်း သတ်မှတ်ပြီးပါပြီ။ ယာဉ်မောင်း - {$booking->driver_name}, {$booking->driver_phone}။ ယာဉ် - {$vehicle}။";
        } else {
            $en = "Driver info updated for booking {$booking->booking_ref} ({$route}). Driver: {$booking->driver_name}, {$booking->driver_phone}. Vehicle: {$vehicle}.";
            $mm = "ဘွတ်ကင် {$booking->booking_ref} ({$mmRoute}) ၏ ယာဉ်မောင်းအချက်အလက်ကို ပြင်ဆင်ထားပါသည်။ ယာဉ်မောင်း - {$booking->driver_name}, {$booking->driver_phone}။ ယာဉ် - {$vehicle}။";
        }

        return "{$appName}\n{$en}\n{$mm}\n{$contact}";
    }
}
