<?php

namespace App\Services\Messaging;

use App\Models\Conversation;
use App\Models\ConversationParticipant;
use Illuminate\Support\Facades\Cache;

class ConversationStateService
{
    public function activeParticipantIds(Conversation|int $conversation): array
    {
        $conversationId = $conversation instanceof Conversation ? $conversation->id : $conversation;

        return ConversationParticipant::query()
            ->where('conversation_id', $conversationId)
            ->whereNull('left_at')
            ->pluck('user_id')
            ->map(fn ($id) => (int) $id)
            ->all();
    }

    public function touchConversationCachesForUsers(array $userIds): void
    {
        foreach (array_unique($userIds) as $userId) {
            if (! $userId) {
                continue;
            }

            $versionKey = "messages:conversations:version:{$userId}";
            Cache::add($versionKey, 1, now()->addDay());
            Cache::increment($versionKey);
        }
    }
}
