<?php

namespace App\Models;

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

/**
 * One mail this installation sent.
 *
 * The register exists so that "did they ever get it, and when?" has an answer
 * inside the console. Before this, the only record was whatever `sent_at`
 * column the feature in question happened to keep — one per feature, only for
 * the features that thought of it — and everything else lived in the mail
 * server's log on another machine.
 *
 * Written from the MessageSent event, so a row here means the transport
 * accepted the message. That is the strongest claim an application can honestly
 * make; what the receiving server did with it afterwards is not ours to know,
 * and a column called `delivered` would be pretending otherwise.
 */
class SentMail extends Model
{
    use HasFactory;
    use HasUuid;

    protected $fillable = [
        'customer_id', 'to', 'subject', 'mailable', 'from_operator', 'body', 'sent_at',
    ];

    protected function casts(): array
    {
        return [
            'from_operator' => 'boolean',
            'sent_at' => 'datetime',
        ];
    }

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

    /**
     * The mailable's short name, for a column that has to fit.
     *
     * "OrderConfirmationMail", not "App\Mail\OrderConfirmationMail" — the
     * namespace is the same on every row and tells the reader nothing.
     */
    public function kind(): string
    {
        return $this->mailable === null ? '—' : class_basename($this->mailable);
    }
}
