<?php

namespace App\Services\Providers;

use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\OperationRunService;
use App\Support\Auth\Capabilities;
use App\Support\Operations\ExecutionAuthorityMode;
use App\Support\Operations\OperationRunCapabilityResolver;
use App\Support\Providers\Capabilities\ProviderCapabilityEvaluator;
use App\Support\Providers\Capabilities\ProviderCapabilityResult;
use App\Support\Providers\ProviderNextStepsRegistry;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Providers\TargetScope\ProviderConnectionTargetScopeDescriptor;
use App\Support\Providers\TargetScope\ProviderConnectionTargetScopeNormalizer;
use App\Support\Providers\TargetScope\ProviderIdentityContextMetadata;
use App\Support\Verification\BlockedVerificationReportFactory;
use App\Support\Verification\StaleQueuedVerificationReportFactory;
use App\Support\Verification\VerificationReportWriter;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use ReflectionFunction;
use ReflectionMethod;

final class ProviderOperationStartGate
{
    public function __construct(
        private readonly OperationRunService $runs,
        private readonly ProviderOperationRegistry $registry,
        private readonly ProviderConnectionResolver $resolver,
        private readonly ProviderNextStepsRegistry $nextStepsRegistry,
        private readonly OperationRunCapabilityResolver $capabilityResolver,
        private readonly ProviderConnectionTargetScopeNormalizer $targetScopeNormalizer,
        private readonly ProviderCapabilityEvaluator $providerCapabilityEvaluator,
    ) {}

    /**
     * @param  array<string, mixed>  $extraContext
     */
    public function start(
        ManagedEnvironment $tenant,
        ?ProviderConnection $connection,
        string $operationType,
        callable $dispatcher,
        ?User $initiator = null,
        array $extraContext = [],
    ): ProviderOperationStartResult {
        $definition = $this->registry->get($operationType);
        $binding = $this->resolveProviderBinding($operationType, $connection);

        if (($binding['binding_status'] ?? null) !== ProviderOperationRegistry::BINDING_ACTIVE) {
            return $this->startBlocked(
                tenant: $tenant,
                operationType: $operationType,
                provider: (string) ($binding['provider'] ?? 'unknown'),
                module: (string) $definition['module'],
                reasonCode: ProviderReasonCodes::ProviderBindingUnsupported,
                extensionReasonCode: 'ext.provider_binding_missing',
                reasonMessage: 'No explicit provider binding supports this operation/provider combination.',
                connection: $connection,
                initiator: $initiator,
                extraContext: array_merge($extraContext, [
                    'provider_binding' => $this->bindingContext($binding),
                ]),
            );
        }

        $resolution = $connection instanceof ProviderConnection
            ? $this->resolver->validateConnection($tenant, (string) $binding['provider'], $connection)
            : $this->resolver->resolveDefault($tenant, (string) $binding['provider']);

        if (! $resolution->resolved || ! $resolution->connection instanceof ProviderConnection) {
            return $this->startBlocked(
                tenant: $tenant,
                operationType: $operationType,
                provider: (string) $binding['provider'],
                module: (string) $definition['module'],
                reasonCode: $resolution->effectiveReasonCode(),
                extensionReasonCode: $resolution->extensionReasonCode,
                reasonMessage: $resolution->message,
                connection: $resolution->connection ?? $connection,
                initiator: $initiator,
                extraContext: array_merge($extraContext, [
                    'provider_binding' => $this->bindingContext($binding),
                ]),
            );
        }

        return DB::transaction(function () use ($tenant, $operationType, $dispatcher, $initiator, $extraContext, $definition, $binding, $resolution): ProviderOperationStartResult {
            $connection = $resolution->connection;

            if (! $connection instanceof ProviderConnection) {
                throw new InvalidArgumentException('Resolved provider connection is missing.');
            }

            $lockedConnection = ProviderConnection::query()
                ->whereKey($connection->getKey())
                ->lockForUpdate()
                ->firstOrFail();

            $activeRun = OperationRun::query()
                ->where('managed_environment_id', $tenant->getKey())
                ->active()
                ->where('context->provider_connection_id', (int) $lockedConnection->getKey())
                ->orderByDesc('id')
                ->lockForUpdate()
                ->first();

            if ($activeRun instanceof OperationRun) {
                if ($this->runs->isStaleQueuedRun($activeRun)) {
                    $this->runs->failStaleQueuedRun($activeRun);

                    if ($activeRun->type === 'provider.connection.check') {
                        VerificationReportWriter::write(
                            run: $activeRun,
                            checks: StaleQueuedVerificationReportFactory::checks($activeRun),
                            identity: StaleQueuedVerificationReportFactory::identity($activeRun),
                        );

                        $activeRun->refresh();
                    }

                    $activeRun = null;
                }
            }

            if ($activeRun instanceof OperationRun) {
                if ($activeRun->type === $operationType) {
                    return ProviderOperationStartResult::deduped($activeRun);
                }

                return ProviderOperationStartResult::scopeBusy($activeRun);
            }

            $providerCapabilityResults = $this->providerCapabilityEvaluator->evaluateForOperation(
                tenant: $tenant,
                connection: $lockedConnection,
                operationType: $operationType,
            );
            $blockingCapability = $this->providerCapabilityEvaluator->primaryBlockingResult($providerCapabilityResults);

            if ($blockingCapability instanceof ProviderCapabilityResult) {
                return $this->startBlocked(
                    tenant: $tenant,
                    operationType: $operationType,
                    provider: (string) $binding['provider'],
                    module: (string) $definition['module'],
                    reasonCode: $blockingCapability->reasonCode ?? ProviderReasonCodes::ProviderPermissionMissing,
                    reasonMessage: $blockingCapability->primaryMessage,
                    connection: $lockedConnection,
                    initiator: $initiator,
                    extraContext: array_merge($extraContext, [
                        'provider_binding' => $this->bindingContext($binding),
                        'provider_capabilities' => $this->providerCapabilityContext($providerCapabilityResults),
                        'provider_capability' => $blockingCapability->toArray(),
                        'provider_capability_status' => $blockingCapability->status->value,
                    ]),
                );
            }

            $context = array_merge($extraContext, [
                'execution_authority_mode' => is_string($extraContext['execution_authority_mode'] ?? null)
                    ? $extraContext['execution_authority_mode']
                    : ($initiator instanceof User ? ExecutionAuthorityMode::ActorBound->value : ExecutionAuthorityMode::SystemAuthority->value),
                'required_capability' => $this->resolveRequiredCapability($operationType, $extraContext),
                'provider' => $lockedConnection->provider,
                'module' => $definition['module'],
                'provider_binding' => $this->bindingContext($binding),
                'required_provider_capabilities' => $this->registry->providerCapabilityKeysForOperation($operationType),
                'provider_capabilities' => $this->providerCapabilityContext($providerCapabilityResults),
                'provider_connection_id' => (int) $lockedConnection->getKey(),
                'connection_type' => $lockedConnection->connection_type?->value ?? $lockedConnection->connection_type,
                'target_scope' => $this->targetScopeContextForConnection($lockedConnection),
                'provider_context' => $this->providerContextForConnection($lockedConnection),
            ]);

            $run = $this->runs->ensureRunWithIdentity(
                tenant: $tenant,
                type: $operationType,
                identityInputs: [
                    'provider_connection_id' => (int) $lockedConnection->getKey(),
                ],
                context: $context,
                initiator: $initiator,
            );

            $dispatched = false;

            if ($run->wasRecentlyCreated) {
                $this->invokeDispatcher($dispatcher, $run);
                $dispatched = true;
            }

            return ProviderOperationStartResult::started($run, $dispatched);
        });
    }

    /**
     * @param  array<string, mixed>  $extraContext
     */
    private function startBlocked(
        ManagedEnvironment $tenant,
        string $operationType,
        string $provider,
        string $module,
        string $reasonCode,
        ?string $extensionReasonCode = null,
        ?string $reasonMessage = null,
        ?ProviderConnection $connection = null,
        ?User $initiator = null,
        array $extraContext = [],
    ): ProviderOperationStartResult {
        $context = array_merge($extraContext, [
            'execution_authority_mode' => is_string($extraContext['execution_authority_mode'] ?? null)
                ? $extraContext['execution_authority_mode']
                : ($initiator instanceof User ? ExecutionAuthorityMode::ActorBound->value : ExecutionAuthorityMode::SystemAuthority->value),
            'required_capability' => $this->resolveRequiredCapability($operationType, $extraContext),
            'provider' => $provider,
            'module' => $module,
            'required_provider_capabilities' => $this->registry->providerCapabilityKeysForOperation($operationType),
            'target_scope' => $connection instanceof ProviderConnection
                ? $this->targetScopeContextForConnection($connection)
                : $this->targetScopeContextForTenant($tenant, $provider),
        ]);

        $identityInputs = [
            'provider' => $provider,
            'reason_code' => $reasonCode,
        ];

        if (is_string($extensionReasonCode) && $extensionReasonCode !== '') {
            $context['reason_code_extension'] = $extensionReasonCode;
            $identityInputs['reason_code_extension'] = $extensionReasonCode;
        }

        if ($connection instanceof ProviderConnection) {
            $context['provider_connection_id'] = (int) $connection->getKey();
            $context['connection_type'] = $connection->connection_type?->value ?? $connection->connection_type;
            $context['provider_context'] = $this->providerContextForConnection($connection);
            $identityInputs['provider_connection_id'] = (int) $connection->getKey();
        }

        $run = $this->runs->ensureRunWithIdentity(
            tenant: $tenant,
            type: $operationType,
            identityInputs: $identityInputs,
            context: $context,
            initiator: $initiator,
        );

        $run = $this->runs->finalizeBlockedRun(
            $run,
            reasonCode: ProviderReasonCodes::isKnown($reasonCode) ? $reasonCode : ProviderReasonCodes::UnknownError,
            nextSteps: $this->nextStepsRegistry->forReason($tenant, $reasonCode, $connection),
            message: $reasonMessage,
        );

        if ($operationType === 'provider.connection.check') {
            VerificationReportWriter::write(
                run: $run,
                checks: BlockedVerificationReportFactory::checks($run),
                identity: BlockedVerificationReportFactory::identity($run),
            );

            $run->refresh();
        }

        return ProviderOperationStartResult::blocked($run);
    }

    /**
     * @param  array<int, ProviderCapabilityResult>  $results
     * @return array<int, array<string, mixed>>
     */
    private function providerCapabilityContext(array $results): array
    {
        return array_map(
            static fn (ProviderCapabilityResult $result): array => $result->toArray(),
            $results,
        );
    }

    private function invokeDispatcher(callable $dispatcher, OperationRun $run): void
    {
        $ref = null;

        if (is_array($dispatcher) && count($dispatcher) === 2) {
            $ref = new ReflectionMethod($dispatcher[0], (string) $dispatcher[1]);
        } elseif (is_string($dispatcher) && str_contains($dispatcher, '::')) {
            [$class, $method] = explode('::', $dispatcher, 2);
            $ref = new ReflectionMethod($class, $method);
        } elseif ($dispatcher instanceof \Closure) {
            $ref = new ReflectionFunction($dispatcher);
        } elseif (is_object($dispatcher) && method_exists($dispatcher, '__invoke')) {
            $ref = new ReflectionMethod($dispatcher, '__invoke');
        }

        if ($ref && $ref->getNumberOfParameters() >= 1) {
            $dispatcher($run);

            return;
        }

        $dispatcher();
    }

    /**
     * @return array{operation_type: string, provider: string, binding_status: string, handler_notes: string, exception_notes: string}
     */
    private function resolveProviderBinding(string $operationType, ?ProviderConnection $connection): array
    {
        if ($connection instanceof ProviderConnection) {
            $provider = trim((string) $connection->provider);

            return $this->registry->bindingFor($operationType, $provider)
                ?? $this->registry->unsupportedBinding($operationType, $provider);
        }

        return $this->registry->activeBindingFor($operationType)
            ?? $this->registry->unsupportedBinding($operationType, 'unknown');
    }

    /**
     * @param  array{operation_type: string, provider: string, binding_status: string, handler_notes: string, exception_notes: string}  $binding
     * @return array{provider: string, binding_status: string, handler_notes: string, exception_notes: string}
     */
    private function bindingContext(array $binding): array
    {
        return [
            'provider' => (string) $binding['provider'],
            'binding_status' => (string) $binding['binding_status'],
            'handler_notes' => (string) $binding['handler_notes'],
            'exception_notes' => (string) $binding['exception_notes'],
        ];
    }

    /**
     * @return array{
     *     provider: string,
     *     scope_kind: string,
     *     scope_identifier: string,
     *     scope_display_name: string,
     *     shared_label: string,
     *     shared_help_text: string
     * }
     */
    private function targetScopeContextForConnection(ProviderConnection $connection): array
    {
        try {
            return $this->targetScopeNormalizer->descriptorForConnection($connection)->toArray();
        } catch (InvalidArgumentException) {
            $identifier = $connection->tenant instanceof ManagedEnvironment
                ? trim($connection->tenant->providerTenantContext())
                : '';

            if ($identifier === '') {
                $identifier = trim((string) $connection->entra_tenant_id);
            }

            return ProviderConnectionTargetScopeDescriptor::fromInput(
                provider: (string) $connection->provider,
                scopeKind: ProviderConnectionTargetScopeDescriptor::SCOPE_KIND_TENANT,
                scopeIdentifier: $identifier !== '' ? $identifier : (string) $connection->getKey(),
                scopeDisplayName: (string) ($connection->tenant?->name ?? $connection->display_name ?? $identifier),
            )->toArray();
        }
    }

    /**
     * @return array{
     *     provider: string,
     *     scope_kind: string,
     *     scope_identifier: string,
     *     scope_display_name: string,
     *     shared_label: string,
     *     shared_help_text: string
     * }
     */
    private function targetScopeContextForTenant(ManagedEnvironment $tenant, string $provider): array
    {
        $identifier = trim($tenant->providerTenantContext());

        return ProviderConnectionTargetScopeDescriptor::fromInput(
            provider: $provider !== '' ? $provider : 'unknown',
            scopeKind: ProviderConnectionTargetScopeDescriptor::SCOPE_KIND_TENANT,
            scopeIdentifier: $identifier,
            scopeDisplayName: (string) ($tenant->name ?? $identifier),
        )->toArray();
    }

    /**
     * @return array{provider: string, details: list<array<string, string>>}
     */
    private function providerContextForConnection(ProviderConnection $connection): array
    {
        return [
            'provider' => (string) $connection->provider,
            'details' => array_map(
                static fn (ProviderIdentityContextMetadata $detail): array => $detail->toArray(),
                $this->targetScopeNormalizer->contextualIdentityDetailsForConnection($connection),
            ),
        ];
    }

    /**
     * @param  array<string, mixed>  $extraContext
     */
    private function resolveRequiredCapability(string $operationType, array $extraContext): ?string
    {
        if (is_string($extraContext['required_capability'] ?? null) && trim((string) $extraContext['required_capability']) !== '') {
            return trim((string) $extraContext['required_capability']);
        }

        if ($this->registry->isAllowed($operationType)) {
            $definition = $this->registry->get($operationType);
            $requiredCapability = $definition['required_capability'] ?? null;

            if (is_string($requiredCapability) && trim($requiredCapability) !== '') {
                return trim($requiredCapability);
            }
        }

        if ($this->registry->isAllowed($operationType)) {
            return Capabilities::PROVIDER_RUN;
        }

        return $this->capabilityResolver->requiredExecutionCapabilityForType($operationType);
    }
}
