<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Contracts\Repositories\ConversationRepositoryInterface;
use App\Models\Conversation;
use Illuminate\Database\Eloquent\Collection;

final class EloquentConversationRepository implements ConversationRepositoryInterface
{
    /**
     * Find conversation by ID
     */
    public function findById(int $id): ?Conversation
    {
        return Conversation::with(['property', 'guest', 'owner'])->find($id);
    }

    /**
     * Get or create a conversation
     */
    public function getOrCreate(int $propertyId, int $guestId, int $ownerId): Conversation
    {
        return Conversation::firstOrCreate(
            [
                'property_id' => $propertyId,
                'guest_id' => $guestId,
            ],
            [
                'owner_id' => $ownerId,
                'last_message_at' => now(),
                'last_message_preview' => '',
                'guest_unread_count' => 0,
                'owner_unread_count' => 0,
            ]
        );
    }

    /**
     * Get all conversations for a user
     */
    public function getForUser(int $userId, string $userType): Collection
    {
        $query = Conversation::with(['property', 'guest', 'owner']);

        if ($userType === 'guest') {
            $query->where('guest_id', $userId);
        } else {
            $query->where('owner_id', $userId);
        }

        return $query->orderByDesc('last_message_at')->get();
    }

    /**
     * Update conversation metadata
     */
    public function updateMetadata(int $conversationId, array $data): bool
    {
        Conversation::where('id', $conversationId)->update($data);

        return true;
    }

    /**
     * Mark messages as read
     */
    public function markAsRead(int $conversationId, string $userType): bool
    {
        $column = $userType === 'guest' ? 'guest_unread_count' : 'owner_unread_count';

        Conversation::where('id', $conversationId)->update([
            $column => 0,
        ]);

        return true;
    }

    /**
     * Increment unread count
     */
    public function incrementUnreadCount(int $conversationId, string $recipientType): bool
    {
        $column = $recipientType === 'guest' ? 'guest_unread_count' : 'owner_unread_count';

        Conversation::where('id', $conversationId)->increment($column);

        return true;
    }

    /**
     * Get total unread count for a user
     */
    public function getTotalUnreadCount(int $userId, string $userType): int
    {
        $column = $userType === 'guest' ? 'guest_unread_count' : 'owner_unread_count';
        $userColumn = $userType === 'guest' ? 'guest_id' : 'owner_id';

        return (int) Conversation::where($userColumn, $userId)->sum($column);
    }
}
