<?php

namespace App\Http\Controllers;

use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Models\ManagedEnvironmentOnboardingSession;
use App\Services\Intune\AuditLogger;
use App\Support\Providers\ProviderConnectionType;
use App\Support\Providers\ProviderConsentStatus;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Providers\ProviderVerificationStatus;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class AdminConsentCallbackController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(
        Request $request,
        AuditLogger $auditLogger,
    ): View {
        $expectedState = $request->session()->pull('environment_onboard_state');
        $workspaceId = $request->session()->pull('environment_onboard_workspace_id');
        $tenantKey = $request->string('tenant')->toString();
        $state = $request->string('state')->toString();
        $tenantIdentifier = $tenantKey ?: $this->parseState($state);

        if ($expectedState && $expectedState !== $state) {
            abort(ResponseAlias::HTTP_FORBIDDEN, 'Invalid consent state');
        }

        abort_if(empty($tenantIdentifier), 404);

        $tenant = $this->resolveTenant($tenantIdentifier, is_numeric($workspaceId) ? (int) $workspaceId : null);

        $error = $request->string('error')->toString() ?: null;
        $consentGranted = $request->has('admin_consent')
            ? filter_var($request->input('admin_consent'), FILTER_VALIDATE_BOOLEAN)
            : null;

        $status = match (true) {
            $error !== null => 'error',
            $consentGranted === false => 'consent_denied',
            $consentGranted === true => 'ok',
            default => 'pending',
        };

        $connection = $this->upsertProviderConnectionForConsent(
            tenant: $tenant,
            status: $status,
            error: $error,
        );

        $this->invalidateResumableOnboardingVerificationState($tenant, $connection);

        $legacyStatus = $status === 'ok' ? 'success' : 'failed';
        $auditMetadata = [
            'source' => 'admin.consent.callback',
            'workspace_id' => (int) $connection->workspace_id,
            'status' => $status,
            'state' => $state,
            'error' => $error,
            'consent' => $consentGranted,
            'provider_connection_id' => (int) $connection->getKey(),
            'provider' => (string) $connection->provider,
            'entra_tenant_id' => (string) $connection->entra_tenant_id,
            'connection_type' => $connection->connection_type->value,
            'consent_status' => $connection->consent_status->value,
            'verification_status' => $connection->verification_status->value,
        ];

        $auditLogger->log(
            tenant: $tenant,
            action: 'tenant.consent.callback',
            context: [
                'metadata' => $auditMetadata,
            ],
            status: $legacyStatus,
            resourceType: 'provider_connection',
            resourceId: (string) $connection->getKey(),
        );

        $auditLogger->log(
            tenant: $tenant,
            action: 'provider_connection.consent_result',
            context: [
                'metadata' => $auditMetadata,
            ],
            status: $legacyStatus,
            resourceType: 'provider_connection',
            resourceId: (string) $connection->getKey(),
        );

        return view('admin-consent-callback', [
            'tenant' => $tenant,
            'connection' => $connection,
            'status' => $status,
            'error' => $error,
            'consentGranted' => $consentGranted,
            'verificationStateLabel' => $this->verificationStateLabel($connection),
        ]);
    }

    private function resolveTenant(string $tenantIdentifier, ?int $workspaceId): ManagedEnvironment
    {
        /** @var ManagedEnvironment|null $tenant */
        $tenant = ManagedEnvironment::withTrashed()
            ->forTenant($tenantIdentifier)
            ->first();

        if ($tenant?->trashed()) {
            $tenant->restore();
        }

        if ($tenant instanceof ManagedEnvironment) {
            if ($tenant->workspace_id === null && $workspaceId !== null) {
                $tenant->forceFill(['workspace_id' => $workspaceId])->save();
            }

            return $tenant;
        }

        abort_if($workspaceId === null, ResponseAlias::HTTP_FORBIDDEN, 'Missing workspace context');

        return ManagedEnvironment::create([
            'managed_environment_id' => $tenantIdentifier,
            'name' => 'New ManagedEnvironment',
            'workspace_id' => $workspaceId,
        ]);
    }

    private function upsertProviderConnectionForConsent(ManagedEnvironment $tenant, string $status, ?string $error): ProviderConnection
    {
        $hasDefault = ProviderConnection::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('provider', 'microsoft')
            ->where('is_default', true)
            ->exists();

        $consentStatus = match ($status) {
            'ok' => ProviderConsentStatus::Granted,
            'error' => ProviderConsentStatus::Failed,
            default => ProviderConsentStatus::Required,
        };
        $verificationStatus = ProviderVerificationStatus::Unknown;
        $reasonCode = match ($status) {
            'ok' => null,
            'error' => ProviderReasonCodes::ProviderAuthFailed,
            default => ProviderReasonCodes::ProviderConsentMissing,
        };

        $connection = ProviderConnection::query()->updateOrCreate(
            [
                'managed_environment_id' => (int) $tenant->getKey(),
                'provider' => 'microsoft',
                'entra_tenant_id' => (string) ($tenant->graphTenantId() ?? $tenant->managed_environment_id ?? $tenant->external_id),
            ],
            [
                'workspace_id' => (int) $tenant->workspace_id,
                'display_name' => (string) ($tenant->name ?? 'Microsoft Connection'),
                'is_enabled' => true,
                'connection_type' => ProviderConnectionType::Platform->value,
                'consent_status' => $consentStatus->value,
                'consent_granted_at' => $status === 'ok' ? now() : null,
                'consent_last_checked_at' => now(),
                'consent_error_code' => $status === 'error' ? $reasonCode : null,
                'consent_error_message' => $status === 'error' ? $error : null,
                'verification_status' => $verificationStatus->value,
                'migration_review_required' => false,
                'migration_reviewed_at' => null,
                'last_error_reason_code' => $reasonCode,
                'last_error_message' => $status === 'ok' ? null : $error,
                'is_default' => $hasDefault ? false : true,
            ],
        );

        $connection->credential()->delete();

        if (! $hasDefault && ! $connection->is_default) {
            $connection->makeDefault();
        }

        return $connection->fresh();
    }

    private function parseState(?string $state): ?string
    {
        if (empty($state)) {
            return null;
        }

        if (str_contains($state, '|')) {
            [, $value] = explode('|', $state, 2);

            return $value;
        }

        return $state;
    }

    private function verificationStateLabel(ProviderConnection $connection): string
    {
        $verificationStatus = $connection->verification_status instanceof ProviderVerificationStatus
            ? $connection->verification_status
            : ProviderVerificationStatus::tryFrom((string) $connection->verification_status);

        if ($verificationStatus === ProviderVerificationStatus::Unknown) {
            return $connection->consent_status === ProviderConsentStatus::Granted
                ? 'Needs verification'
                : 'Not verified';
        }

        return ucfirst(str_replace('_', ' ', $verificationStatus?->value ?? 'unknown'));
    }

    private function invalidateResumableOnboardingVerificationState(ManagedEnvironment $tenant, ProviderConnection $connection): void
    {
        ManagedEnvironmentOnboardingSession::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->resumable()
            ->each(function (ManagedEnvironmentOnboardingSession $draft) use ($connection): void {
                $state = is_array($draft->state) ? $draft->state : [];
                $providerConnectionId = $state['provider_connection_id'] ?? null;
                $providerConnectionId = is_numeric($providerConnectionId) ? (int) $providerConnectionId : null;

                if ($providerConnectionId !== null && $providerConnectionId !== (int) $connection->getKey()) {
                    return;
                }

                unset(
                    $state['verification_operation_run_id'],
                    $state['verification_run_id'],
                    $state['bootstrap_operation_runs'],
                    $state['bootstrap_operation_types'],
                    $state['bootstrap_run_ids'],
                );

                $state['connection_recently_updated'] = true;

                $draft->state = $state;
                $draft->save();
            });
    }
}
