<?php

namespace App\Jobs;

use App\Models\SmsSend;
use App\Services\ClickSendSmsService;
use App\Support\SendStatus;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Throwable;

class SendSmsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 5;
    public int $timeout = 20;

    public function __construct(public SmsSend $smsSend) {}

    public function handle(ClickSendSmsService $clicksend): void
    {
        // Hard stop if already sent (idempotency supremacy)
        if ($this->smsSend->status === SendStatus::SENT) {
            return;
        }

        $this->smsSend->update([
            'status'          => SendStatus::SENDING,
            'attempts'        => $this->smsSend->attempts + 1,
            'last_attempt_at' => now(),
            'provider'        => 'clicksend',
        ]);

        try {
            $response = $clicksend->send(
                to: $this->smsSend->to_number,
                message: $this->smsSend->message,
                from: $this->smsSend->from_number
            );

            $message = $response['data']['messages'][0] ?? [];

            $this->smsSend->update([
                'status'               => SendStatus::SENT,
                'sent_at'              => now(),
                'provider_message_id'  => $message['message_id'] ?? null,
                'provider_response'    => $message,
            ]);

        } catch (Throwable $e) {
            $this->smsSend->update([
                'status'        => SendStatus::FAILED,
                'error_message' => $e->getMessage(),
            ]);

            throw $e;
        }
    }
}
