<?php

namespace App\Services\Graph;

use App\Models\ManagedEnvironment;
use App\Services\Providers\MicrosoftGraphOptionsResolver;
use Illuminate\Support\Facades\Cache;

class AssignmentFilterResolver
{
    public function __construct(
        private readonly GraphClientInterface $graphClient,
        private readonly MicrosoftGraphOptionsResolver $graphOptionsResolver,
    ) {}

    /**
     * @param  array<int, string>  $filterIds
     * @return array<int, array{id:string,displayName:?string}>
     */
    public function resolve(array $filterIds, ?ManagedEnvironment $tenant = null): array
    {
        if (empty($filterIds)) {
            return [];
        }

        $allFilters = $this->fetchAllFilters($tenant);

        return array_values(array_filter($allFilters, function (array $filter) use ($filterIds): bool {
            return in_array($filter['id'] ?? null, $filterIds, true);
        }));
    }

    /**
     * @return array<int, array{id:string,displayName:?string}>
     */
    private function fetchAllFilters(?ManagedEnvironment $tenant = null): array
    {
        $cacheKey = $tenant ? "assignment_filters:tenant:{$tenant->id}" : 'assignment_filters:all';

        return Cache::remember($cacheKey, 3600, function () use ($tenant): array {
            $options = ['query' => ['$select' => 'id,displayName']];

            if ($tenant) {
                $options = array_merge($options, $this->graphOptionsResolver->resolveForTenant($tenant));
            }

            $response = $this->graphClient->request(
                'GET',
                '/deviceManagement/assignmentFilters',
                $options
            );

            return $response->data['value'] ?? [];
        });
    }
}
