<?php

namespace App\Models\Contact\Send;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class SmsSend extends Model
{
    protected $fillable = [
        'sendable_id',
        'sendable_type',
        'to_number',
        'from_number',
        'message',
        'scheduled_for',
        'sent_at',
        'status',
        'attempts',
        'provider',
        'provider_message_id',
        'provider_response',
        'error_message',
    ];

    protected $casts = [
        'provider_response' => 'array',
        'scheduled_for' => 'datetime',
        'sent_at' => 'datetime',
        'last_attempt_at' => 'datetime',
    ];

    public function sendable(): MorphTo {
        return $this->morphTo();
    }

    public function scopeDue($query) {
        return $query
            ->whereIn('status', ['pending', 'scheduled'])
            ->where(function ($q)
            {
                $q->whereNull('scheduled_for')
                    ->orWhere('scheduled_for', '<=', now());
            });
    }
}
