<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

enum EmailLogStatus: string
{
    case Queued = 'queued';
    case Sending = 'sending';
    case Sent = 'sent';
    case Failed = 'failed';
    case Bounced = 'bounced';
    case Deferred = 'deferred';
}

class EmailLog extends Model
{
    protected $fillable = [
        'uuid',
        'template_id',
        'mail_profile_id',
        'user_id',
        'correlation_id',
        'to_email',
        'to_recipients',
        'to_name',
        'cc',
        'bcc',
        'from_email',
        'from_name',
        'reply_to',
        'subject',
        'body_html_hash',
        'body_text_preview',
        'attachments',
        'embed_mode',
        'status',
        'error_code',
        'error_message',
        'transport',
        'headers',
        'attempt',
        'duration_ms',
        'client_id',
        'client_case_id',
        'contract_id',
        'extra_context',
        'queued_at',
        'started_at',
        'sent_at',
        'failed_at',
        'ip',
    ];

    protected function casts(): array
    {
        return [
            'status' => EmailLogStatus::class,
            'cc' => 'array',
            'bcc' => 'array',
            'to_recipients' => 'array',
            'attachments' => 'array',
            'headers' => 'array',
            'extra_context' => 'array',
            'attempt' => 'integer',
            'duration_ms' => 'integer',
            'queued_at' => 'datetime',
            'started_at' => 'datetime',
            'sent_at' => 'datetime',
            'failed_at' => 'datetime',
        ];
    }

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

    public function body(): HasOne
    {
        return $this->hasOne(EmailLogBody::class, 'email_log_id');
    }

    public function activities(): BelongsToMany
    {
        return $this->belongsToMany(Activity::class, 'activity_email_logs');
    }
}
