<?php

namespace App\Models;

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

class DisputeMessage extends Model
{
    use HasFactory;

    protected $fillable = [
        'dispute_id',
        'sent_by',
        'message',
        'sender_role',
        'is_internal',
        'attachments',
        'read_at',
    ];

    protected $casts = [
        'is_internal' => 'boolean',
        'attachments' => 'array',
        'read_at'     => 'datetime',
    ];

    // ============================================================
    // Scopes
    // ============================================================
    public function scopePublic($query)
    {
        return $query->where('is_internal', false);
    }

    public function scopeInternal($query)
    {
        return $query->where('is_internal', true);
    }

    public function scopeUnread($query)
    {
        return $query->whereNull('read_at');
    }

    // ============================================================
    // Helpers
    // ============================================================
    public function isInternal(): bool
    {
        return $this->is_internal === true;
    }

    public function isRead(): bool
    {
        return $this->read_at !== null;
    }

    public function markAsRead(): void
    {
        if (!$this->read_at) {
            $this->update(['read_at' => now()]);
        }
    }

    public function getSenderRoleLabel(): string
    {
        return match($this->sender_role) {
            'advertiser'  => 'Advertiser',
            'media_owner' => 'Media Owner',
            'admin'       => 'Nexus Admin',
            'system'      => 'System',
            default       => ucfirst($this->sender_role),
        };
    }

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

    // ============================================================
    // Relationships
    // ============================================================
    public function dispute()
    {
        return $this->belongsTo(Dispute::class);
    }

    public function sentBy()
    {
        return $this->belongsTo(User::class, 'sent_by');
    }
}