<?php

namespace App\Services\Platform;

use App\Models\PlatformInstance;
use App\Modules\Lemmy\Services\LemmyApiService;
use Illuminate\Support\Facades\Cache;

class CommunityDirectory
{
    private const TTL_SECONDS = 86400;

    /**
     * @return array<int, array{id: int, name: string, title: string}>
     */
    public function forInstance(PlatformInstance $instance): array
    {
        return Cache::remember(
            self::cacheKey($instance),
            self::TTL_SECONDS,
            fn () => $this->makeApi($instance->url)->listCommunities()
        );
    }

    public function forget(PlatformInstance $instance): void
    {
        Cache::forget(self::cacheKey($instance));
    }

    public function has(PlatformInstance $instance, int $communityId): bool
    {
        return collect($this->forInstance($instance))
            ->contains(fn (array $community) => $community['id'] === $communityId);
    }

    public function name(PlatformInstance $instance, int $communityId): ?string
    {
        return collect($this->forInstance($instance))
            ->firstWhere('id', $communityId)['name'] ?? null;
    }

    protected function makeApi(string $instanceUrl): LemmyApiService
    {
        return new LemmyApiService($instanceUrl);
    }

    private static function cacheKey(PlatformInstance $instance): string
    {
        return "platform:communities:{$instance->id}";
    }
}
