<?php

namespace App\Jobs;

use App\Mail\DailyBranchReportMail;
use App\Models\DailyBranchReportDelivery;
use App\Services\WhatsAppGatewayService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;

class SendDailyBranchReportDelivery implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;
    public int $timeout = 60;
    public array $backoff = [60, 300, 900];

    public function __construct(public readonly int $deliveryId) {}

    public function handle(WhatsAppGatewayService $whatsApp): void
    {
        $delivery = DailyBranchReportDelivery::query()
            ->with(['report.business'])
            ->find($this->deliveryId);

        if (! $delivery || $delivery->status === 'sent') {
            return;
        }

        $delivery->update([
            'status' => 'pending',
            'attempts' => $delivery->attempts + 1,
            'last_attempt_at' => now(),
            'error_message' => null,
        ]);

        try {
            if ($delivery->channel === 'email') {
                Mail::to($delivery->recipient)->send(new DailyBranchReportMail($delivery->report));

                $delivery->update([
                    'status' => 'sent',
                    'provider_response' => 'Accepted by the configured Laravel mail transport.',
                    'sent_at' => now(),
                ]);

                return;
            }

            if ($delivery->channel === 'whatsapp') {
                $result = $whatsApp->sendText(
                    $delivery->report->business,
                    $delivery->recipient,
                    $delivery->report->body_text,
                );

                $delivery->update([
                    'provider_message_id' => $result['message_id'],
                    'provider_response' => $result['response'],
                ]);

                if (! $result['successful']) {
                    throw new RuntimeException('WhatsApp provider rejected the report with HTTP '.($result['status'] ?? 'unknown').'.');
                }

                $delivery->update([
                    'status' => 'sent',
                    'recipient' => $result['recipient'],
                    'sent_at' => now(),
                    'error_message' => null,
                ]);

                return;
            }

            throw new RuntimeException('Unsupported daily branch report channel: '.$delivery->channel);
        } catch (Throwable $exception) {
            $delivery->update([
                'status' => 'failed',
                'error_message' => Str::limit($exception->getMessage(), 4000, '…'),
            ]);

            throw $exception;
        }
    }
}
