<?php

namespace App\Modules\Admin\Tenancy\Services;

use App\Modules\Admin\Tenancy\Models\Tenant;
use Illuminate\Support\Facades\Cache;

class ModuleAccessService
{
    private const CACHE_TTL_SECONDS = 600;

    public function __construct(
        private readonly SubscriptionService $subscriptionService,
    ) {}

    /**
     * Determine whether the given tenant has access to the given module slug
     * through an active (non-expired) subscription.
     */
    public function tenantHasModule(Tenant $tenant, string $moduleSlug): bool
    {
        $slugs = $this->activeModuleSlugsFor($tenant);

        return in_array($moduleSlug, $slugs, true);
    }

    /**
     * @return array<int, string>
     */
    public function activeModuleSlugsFor(Tenant $tenant): array
    {
        return Cache::remember(
            $this->cacheKey($tenant),
            self::CACHE_TTL_SECONDS,
            function () use ($tenant): array {
                $subscription = $this->subscriptionService->activeFor($tenant);
                if ($subscription === null || $subscription->isExpired()) {
                    return [];
                }

                return $subscription->plan
                    ->modules()
                    ->where('is_active', true)
                    ->pluck('slug')
                    ->all();
            }
        );
    }

    public function forgetTenant(Tenant $tenant): void
    {
        Cache::forget($this->cacheKey($tenant));
    }

    private function cacheKey(Tenant $tenant): string
    {
        return 'tenant:'.$tenant->id.':modules';
    }
}
