<?php

namespace App\Models;

use App\Models\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * One mail a customer sent us.
 *
 * The other half of SentMail. A customer who replies by mail instead of using
 * the portal form used to be invisible here: the question sat in somebody's
 * mail client, the answer went out from there, and the console knew nothing.
 *
 * Attachments are names and sizes, never files — see the migration for why.
 */
class InboundMail extends Model
{
    use HasFactory;
    use HasUuid;

    protected $fillable = [
        'customer_id', 'support_request_id', 'message_id', 'from_email', 'from_name',
        'subject', 'body', 'attachments', 'received_at', 'read_at', 'archived_at',
    ];

    protected function casts(): array
    {
        return [
            'attachments' => 'array',
            'received_at' => 'datetime',
            'read_at' => 'datetime',
            'archived_at' => 'datetime',
        ];
    }

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

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

    /** Still in the inbox, i.e. not put away. */
    public function scopeOpen(Builder $query): Builder
    {
        return $query->whereNull('archived_at');
    }

    /**
     * From an address nobody recognises.
     *
     * Not an error state: it is a new enquiry, or a customer writing from their
     * private address. The mail an operator must not miss is exactly this one.
     */
    public function isUnassigned(): bool
    {
        return $this->customer_id === null;
    }

    public function hasAttachments(): bool
    {
        return ! empty($this->attachments);
    }
}
