<?php

namespace App\Models;

use App\Models\Concerns\HasStatusLabels;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class ContactMessage extends Model
{
    use HasFactory;
    use HasStatusLabels;
    use SoftDeletes;

    protected $fillable = [
        'full_name',
        'company',
        'email',
        'phone',
        'service',
        'subject',
        'message',
        'consent_at',
        'status',
        'read_at',
        'replied_at',
        'processed_at',
        'archived_at',
        'ip_address',
        'user_agent',
    ];

    protected $casts = [
        'consent_at' => 'datetime',
        'read_at' => 'datetime',
        'replied_at' => 'datetime',
        'processed_at' => 'datetime',
        'archived_at' => 'datetime',
    ];

    protected $appends = ['status_label', 'name', 'excerpt', 'received_at_demo'];

    public function replies(): HasMany
    {
        return $this->hasMany(ContactMessageReply::class);
    }

    public function scopeOrdered($query)
    {
        return $query->latest();
    }

    protected function name(): Attribute
    {
        return Attribute::get(fn (): string => $this->full_name);
    }

    protected function excerpt(): Attribute
    {
        return Attribute::get(fn (): string => str($this->message)->limit(120)->toString());
    }

    protected function receivedAtDemo(): Attribute
    {
        return Attribute::get(fn (): string => optional($this->created_at)->format('Y-m-d H:i') ?? '—');
    }
}
