<?php

namespace App\Models;

use App\Enums\ActorType;
use App\Enums\MessageType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Message extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'declaration_id',
        'type',
        'body',
        'sent_by_type',
        'sent_by_id',
        'metadata',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'type' => MessageType::class,
            'sent_by_type' => ActorType::class,
            'metadata' => 'array',
        ];
    }

    /**
     * Get the declaration that owns the message.
     *
     * @return BelongsTo<Declaration, $this>
     */
    public function declaration(): BelongsTo
    {
        return $this->belongsTo(Declaration::class);
    }

    /**
     * Get the user who sent the message (when sent_by_type is user).
     *
     * @return BelongsTo<User, $this>
     */
    public function senderUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'sent_by_id');
    }

    /**
     * Get the client who sent the message (when sent_by_type is client).
     *
     * @return BelongsTo<Client, $this>
     */
    public function senderClient(): BelongsTo
    {
        return $this->belongsTo(Client::class, 'sent_by_id');
    }

    /**
     * Get the sender display name.
     */
    public function getSenderNameAttribute(): string
    {
        if ($this->sent_by_type?->is(ActorType::User)) {
            return $this->senderUser?->name ?? '—';
        }

        if ($this->sent_by_type?->is(ActorType::Client)) {
            return $this->senderClient?->company_name ?? 'Client';
        }

        return '—';
    }
}
