<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

final class Conversation extends Model
{
    use HasFactory;

    protected $fillable = [
        'property_id',
        'guest_id',
        'owner_id',
        'last_message_at',
        'last_message_preview',
        'guest_unread_count',
        'owner_unread_count',
    ];

    protected function casts(): array
    {
        return [
            'property_id' => 'integer',
            'guest_id' => 'integer',
            'owner_id' => 'integer',
            'guest_unread_count' => 'integer',
            'owner_unread_count' => 'integer',
            'last_message_at' => 'datetime',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

    /**
     * Get the property this conversation is about
     */
    public function property(): BelongsTo
    {
        return $this->belongsTo(Property::class);
    }

    /**
     * Get the guest in this conversation
     */
    public function guest(): BelongsTo
    {
        return $this->belongsTo(User::class, 'guest_id');
    }

    /**
     * Get the owner in this conversation
     */
    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'owner_id');
    }

    /**
     * Get all messages in this conversation
     */
    public function messages(): HasMany
    {
        return $this->hasMany(Message::class);
    }

    /**
     * Get the other user in the conversation (not the current user)
     */
    public function getOtherUser(int $userId): ?User
    {
        if ($this->guest_id === $userId) {
            return $this->owner;
        }

        if ($this->owner_id === $userId) {
            return $this->guest;
        }

        return null;
    }

    /**
     * Get unread count for a specific user
     */
    public function getUnreadCount(int $userId): int
    {
        if ($this->guest_id === $userId) {
            return $this->guest_unread_count;
        }

        if ($this->owner_id === $userId) {
            return $this->owner_unread_count;
        }

        return 0;
    }

    /**
     * Check if user is part of this conversation
     */
    public function hasUser(int $userId): bool
    {
        return $this->guest_id === $userId || $this->owner_id === $userId;
    }
}
