<?php

namespace App\Models;

use App\Enums\EmailStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class EmailMessage extends Model
{
    protected $fillable = [
        'status',
        'user_id',
        'email_template_id',
        'from_name',
        'from_address',
        'reply_to',
        'to',
        'cc',
        'bcc',
        'subject',
        'body_html',
        'related_type',
        'related_id',
        'related_module',
        'error_message',
        'retry_count',
        'provider_response',
        'scheduled_at',
        'sent_at',
    ];

    protected function casts(): array
    {
        return [
            'status' => EmailStatus::class,
            'cc' => 'array',
            'bcc' => 'array',
            'provider_response' => 'array',
            'scheduled_at' => 'datetime',
            'sent_at' => 'datetime',
        ];
    }

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

    public function template(): BelongsTo
    {
        return $this->belongsTo(EmailTemplate::class, 'email_template_id');
    }

    public function attachments(): HasMany
    {
        return $this->hasMany(EmailAttachment::class);
    }

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