<?php

namespace App\Models\Messenger;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ConversationParticipant extends Model
{
    protected $fillable = [
        'conversation_id',
        'user_id',
        'role',
        'joined_at',
        'left_at',
        'last_seen_at',
        'last_seen_message_id',
        'is_muted',
        'muted_until',
        'notifications_settings',
    ];

    protected $casts = [
        'joined_at' => 'datetime',
        'left_at' => 'datetime',
        'last_seen_at' => 'datetime',
        'is_muted' => 'boolean',
        'muted_until' => 'datetime',
        'notifications_settings' => 'array',
    ];

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

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

    public function lastSeenMessage(): BelongsTo
    {
        return $this->belongsTo(Message::class, 'last_seen_message_id');
    }

    public function markMessageAsSeen(int $messageId): void
    {
        if ($this->last_seen_message_id < $messageId) {
            $this->update([
                'last_seen_message_id' => $messageId,
                'last_seen_at' => now(),
            ]);
        }
    }

    public function isOwner(): bool
    {
        return $this->role === 'owner';
    }

    public function isAdmin(): bool
    {
        return in_array($this->role, ['owner', 'admin']);
    }

    public function isMuted(): bool
    {
        if (!$this->is_muted) {
            return false;
        }

        if ($this->muted_until && $this->muted_until->isPast()) {
            $this->update(['is_muted' => false, 'muted_until' => null]);
            return false;
        }

        return true;
    }

    public function mute(?int $minutes = null): void
    {
        $this->update([
            'is_muted' => true,
            'muted_until' => $minutes ? now()->addMinutes($minutes) : null,
        ]);
    }

    public function unmute(): void
    {
        $this->update([
            'is_muted' => false,
            'muted_until' => null,
        ]);
    }
}
