<?php

namespace App\Models\Contact\Send;

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

class EmailSend extends Model
{
    protected $fillable = [
        'sendable_id',
        'sendable_type',
        'to_email',
        'to_name',
        'from_email',
        'from_name',
        'reply_to',
        'subject',
        'html_body',
        'text_body',
        'template',
        'template_data',
        'attachments',
        'scheduled_for',
        'sent_at',
        'status',
        'attempts',
        'provider',
        'provider_message_id',
        'provider_response',
        'error_message',
        'last_attempt_at',
    ];

    protected $casts = [
        'template_data' => 'array',
        'attachments' => 'array',
        '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());
            });
    }
}
