<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Conversation extends Model
{
    protected $fillable = [
        'item_id',
        'subject',
        'last_message_at',
    ];

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

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

    public function messages(): HasMany
    {
        return $this->hasMany(Message::class)->orderBy('created_at', 'asc');
    }

    public function participants(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'conversation_participants')
            ->withPivot('last_read_at')
            ->withTimestamps();
    }

    public function latestMessage(): BelongsTo
    {
        return $this->belongsTo(Message::class, 'id', 'conversation_id')
            ->latest()
            ->limit(1);
    }

    public function getOtherParticipant($userId)
    {
        return $this->participants()->where('user_id', '!=', $userId)->first();
    }

    public function hasUnreadMessages($userId)
    {
        $participant = $this->participants()->where('user_id', $userId)->first();
        if (!$participant) {
            return false;
        }

        $lastReadAt = $participant->pivot->last_read_at;
        
        return $this->messages()
            ->where('user_id', '!=', $userId)
            ->when($lastReadAt, function ($query) use ($lastReadAt) {
                return $query->where('created_at', '>', $lastReadAt);
            }, function ($query) {
                return $query;
            })
            ->exists();
    }

    public function markAsRead($userId)
    {
        $this->participants()->updateExistingPivot($userId, [
            'last_read_at' => now()
        ]);
    }
}
