<?php

namespace App\Jobs;

use App\Enums\SmsSendStatus;
use App\Models\Coupon;
use App\Models\SmsCampaign;
use App\Models\SmsSendLog;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\SerializesModels;

class SendSmsToCouponJob implements ShouldQueue
{
    use Queueable;
    use SerializesModels;

    public int $tries = 3;

    public function __construct(
        public SmsCampaign $campaign,
        public Coupon $coupon,
    ) {
        $this->onQueue('sms');
    }

    public function handle(): void
    {
        $log = SmsSendLog::query()
            ->where('sms_campaign_id', $this->campaign->id)
            ->where('coupon_id', $this->coupon->id)
            ->first();

        if ($log === null) {
            return;
        }

        if (! is_valid_coupon_phone($this->coupon->phone)) {
            $this->markSkipped($log);

            return;
        }

        $success = sendSMS($this->coupon->phone, $this->campaign->message);

        $log->update([
            'status' => $success ? SmsSendStatus::Sent : SmsSendStatus::Failed,
            'error_message' => $success ? null : 'SMS API request failed',
            'attempted_at' => now(),
        ]);

        $this->campaign->increment($success ? 'sent_count' : 'failed_count');
        $this->markCampaignCompleteIfFinished();

        usleep((int) config('services.sms.bulk_delay_ms', 300) * 1000);
    }

    protected function markSkipped(SmsSendLog $log): void
    {
        if ($log->status === SmsSendStatus::SkippedInvalid) {
            return;
        }

        $log->update([
            'status' => SmsSendStatus::SkippedInvalid,
            'attempted_at' => now(),
        ]);

        $this->campaign->increment('skipped_count');
        $this->markCampaignCompleteIfFinished();
    }

    protected function markCampaignCompleteIfFinished(): void
    {
        $this->campaign->refresh();

        if ($this->campaign->processedCount() >= $this->campaign->recipient_count) {
            $this->campaign->update(['completed_at' => now()]);
        }
    }
}
