<?php

namespace App\Services\Inventory\DependencyTargets;

use App\Models\InventoryItem;
use App\Models\ManagedEnvironment;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;

class DependencyTargetResolver
{
    public function __construct(private readonly FoundationTypeMap $foundationTypeMap) {}

    /**
     * @param  Collection<int, mixed>  $edges
     * @return Collection<int, array<string, mixed>>
     */
    public function attachRenderedTargets(Collection $edges, ManagedEnvironment $tenant): Collection
    {
        $edgeRows = $edges
            ->map(fn ($edge) => $edge instanceof Model ? $edge->toArray() : (array) $edge)
            ->values();

        $targetIdsByFoundationType = [];

        foreach ($edgeRows as $edge) {
            $targetType = Arr::get($edge, 'target_type');
            if ($targetType !== 'foundation_object') {
                continue;
            }

            $foundationType = Arr::get($edge, 'metadata.foundation_type');
            $targetId = Arr::get($edge, 'target_id');

            if (! is_string($foundationType) || $foundationType === '') {
                continue;
            }

            if (! is_string($targetId) || $targetId === '') {
                continue;
            }

            $targetIdsByFoundationType[$foundationType] ??= [];
            $targetIdsByFoundationType[$foundationType][] = $targetId;
        }

        $resolvedMaps = $this->resolveFoundationTargetsFromDb($tenant, $targetIdsByFoundationType);

        return $edgeRows->map(function (array $edge) use ($tenant, $resolvedMaps) {
            $targetType = Arr::get($edge, 'target_type');

            if ($targetType === 'missing') {
                $edge['rendered_target'] = DependencyTargetDto::missing()->toArray();

                return $edge;
            }

            if ($targetType === 'foundation_object') {
                $foundationType = Arr::get($edge, 'metadata.foundation_type');
                $targetId = Arr::get($edge, 'target_id');

                if (! is_string($targetId) || $targetId === '') {
                    $edge['rendered_target'] = DependencyTargetDto::externalReference('')->toArray();

                    return $edge;
                }

                $foundationType = is_string($foundationType) ? $foundationType : null;
                $mapRow = $this->foundationTypeMap->get($foundationType);

                if ($foundationType === 'aad_group') {
                    $label = $mapRow['label'] ?? 'Group (external)';
                    $edge['rendered_target'] = DependencyTargetDto::externalGroupWithLabel($targetId, $label)->toArray();

                    return $edge;
                }

                if (! $mapRow) {
                    $edge['rendered_target'] = DependencyTargetDto::externalReference($targetId, $foundationType)->toArray();

                    return $edge;
                }

                $label = $mapRow['label'] ?? 'External reference';
                $resolved = $foundationType ? ($resolvedMaps[$foundationType][$targetId] ?? null) : null;

                if (! is_array($resolved) || ! array_key_exists('inventory_item_id', $resolved)) {
                    $edge['rendered_target'] = DependencyTargetDto::unresolvedFoundation($label, $foundationType, $targetId)->toArray();

                    return $edge;
                }

                $displayName = $resolved['display_name'] ?? null;
                if (! is_string($displayName) || $displayName === '') {
                    $edge['rendered_target'] = DependencyTargetDto::unresolvedFoundation($label, $foundationType, $targetId)->toArray();

                    return $edge;
                }

                $linkable = (bool) ($mapRow['linkable'] ?? false);

                $edge['rendered_target'] = DependencyTargetDto::resolvedFoundation(
                    $label,
                    $foundationType,
                    $targetId,
                    $displayName,
                    $linkable ? (int) $resolved['inventory_item_id'] : null,
                    $tenant,
                )->toArray();

                return $edge;
            }

            $targetId = Arr::get($edge, 'target_id');
            if (is_string($targetId) && $targetId !== '') {
                $edge['rendered_target'] = DependencyTargetDto::externalReference($targetId, $targetType)->toArray();

                return $edge;
            }

            $edge['rendered_target'] = DependencyTargetDto::externalReference('', $targetType)->toArray();

            return $edge;
        });
    }

    /**
     * @param  array<string, list<string>>  $targetIdsByFoundationType
     * @return array<string, array<string, array{inventory_item_id:int,display_name:?string}>>
     */
    private function resolveFoundationTargetsFromDb(ManagedEnvironment $tenant, array $targetIdsByFoundationType): array
    {
        $resolvableTypes = $this->foundationTypeMap->resolvableFoundationTypes();
        $policyTypeToFoundationType = $this->foundationTypeMap->policyTypeToFoundationType();

        $policyTypes = [];
        $allExternalIds = [];

        foreach ($targetIdsByFoundationType as $foundationType => $targetIds) {
            if (! in_array($foundationType, $resolvableTypes, true)) {
                continue;
            }

            $row = $this->foundationTypeMap->get($foundationType);
            $policyType = $row['inventory_policy_type'] ?? null;
            if (! is_string($policyType) || $policyType === '') {
                continue;
            }

            $policyTypes[] = $policyType;
            foreach ($targetIds as $id) {
                if (is_string($id) && $id !== '') {
                    $allExternalIds[] = $id;
                }
            }
        }

        $policyTypes = array_values(array_unique($policyTypes));
        $allExternalIds = array_values(array_unique($allExternalIds));

        if ($policyTypes === [] || $allExternalIds === []) {
            return [];
        }

        $items = InventoryItem::query()
            ->where('managed_environment_id', $tenant->getKey())
            ->whereIn('policy_type', $policyTypes)
            ->whereIn('external_id', $allExternalIds)
            ->get(['id', 'managed_environment_id', 'policy_type', 'external_id', 'display_name']);

        $resolved = [];

        foreach ($items as $item) {
            $foundationType = $policyTypeToFoundationType[$item->policy_type] ?? null;
            if (! is_string($foundationType) || $foundationType === '') {
                continue;
            }

            $resolved[$foundationType] ??= [];
            $resolved[$foundationType][$item->external_id] = [
                'inventory_item_id' => (int) $item->getKey(),
                'display_name' => is_string($item->display_name) ? $item->display_name : null,
            ];
        }

        return $resolved;
    }
}
