<?php

namespace App\Models;

use App\Enums\WaMessageStatus;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class WaMessage extends Model
{
    use BelongsToTenant;

    protected $table = 'wa_messages';

    protected $fillable = [
        'tenant_id', 'patient_id', 'to_phone', 'template_key', 'body',
        'status', 'direction', 'provider', 'provider_message_id',
        'failure_code', 'failure_reason', 'attempts', 'next_attempt_at',
        'media_path', 'media_mime', 'media_filename',
        'related_type', 'related_id', 'sent_at', 'delivered_at', 'read_at',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'status' => WaMessageStatus::class,
            'next_attempt_at' => 'datetime',
            'sent_at' => 'datetime',
            'delivered_at' => 'datetime',
            'read_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(fn (WaMessage $m) => $m->uuid ??= (string) Str::uuid());
    }

    public function patient(): BelongsTo
    {
        return $this->belongsTo(Patient::class);
    }

    public function related()
    {
        return $this->morphTo();
    }

    public function hasMedia(): bool
    {
        return $this->media_path !== null;
    }

    public function scopeDueForRetry(Builder $q): Builder
    {
        return $q->where('status', WaMessageStatus::Retrying->value)
            ->where('next_attempt_at', '<=', now());
    }
}
