<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class EmailMessage extends Model
{
    protected $table = 'email_messages';

    protected $fillable = [
        'email_folder_id', 'message_id', 'subject', 'from_name', 'from_email',
        'to_name', 'to_email', 'cc', 'bcc', 'body_text', 'body_html',
        'is_read', 'is_starred', 'is_important', 'is_sent', 'is_draft', 'is_trash',
        'received_at', 'sent_at', 'imap_uid'
    ];

    protected $casts = [
        'is_read' => 'boolean',
        'is_starred' => 'boolean',
        'is_important' => 'boolean',
        'is_sent' => 'boolean',
        'is_draft' => 'boolean',
        'is_trash' => 'boolean',
        'received_at' => 'datetime',
        'sent_at' => 'datetime',
    ];

    public function folder(): BelongsTo
    {
        return $this->belongsTo(EmailFolder::class, 'email_folder_id');
    }

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

    public function getExcerptAttribute(): string
    {
        $body = strip_tags($this->body_text ?? $this->body_html ?? '');
        return mb_strimwidth($body, 0, 100, '...');
    }

    public function getBodyForDisplayAttribute(): string
    {
        if ($this->body_html) {
            return $this->body_html;
        }
        return nl2br(e($this->body_text ?? ''));
    }

    public function scopeUnread($query)
    {
        return $query->where('is_read', false);
    }

    public function scopeInbox($query)
    {
        return $query->whereHas('folder', fn($q) => $q->where('type', 'inbox'));
    }

    public function scopeSent($query)
    {
        return $query->where('is_sent', true);
    }
}