<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Email extends Model
{
    /** @use HasFactory<\Database\Factories\EmailFactory> */
    use HasFactory;

    protected $table = 'emails';

    protected $fillable = [
        'unique_id_hash',
        'recipient_email',
        'recipient_name',
        'sender_email',
        'sender_name',
        'domain',
        'subject',
        'preview',
        'attachments_json',
        'attachment_size',
        'is_read',
        'received_at',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'attachments_json' => 'array',
            'attachment_size' => 'integer',
            'is_read' => 'boolean',
            'received_at' => 'datetime',
        ];
    }

    /**
     * Scope: filter emails by recipient address.
     */
    public function scopeForRecipient(Builder $query, string $email): Builder
    {
        return $query->where('recipient_email', $email);
    }

    /**
     * Scope: filter emails by domain.
     */
    public function scopeForDomain(Builder $query, string $domain): Builder
    {
        return $query->where('domain', $domain);
    }

    /**
     * Scope: filter unread emails only.
     */
    public function scopeUnread(Builder $query): Builder
    {
        return $query->where('is_read', false);
    }
}
