<?php

declare(strict_types=1);

namespace App\Support\Navigation;

use App\Support\Tenants\TenantInteractionLane;
use Illuminate\Http\Request;

enum AdminSurfaceScope: string
{
    case WorkspaceWideSurface = 'workspace_wide_surface';
    case WorkspaceScoped = 'workspace_scoped';
    case WorkspaceChooserException = 'workspace_chooser_exception';
    case EnvironmentBound = 'environment_bound';
    case EnvironmentScopedEvidence = 'environment_scoped_evidence';
    case OnboardingWorkflow = 'onboarding_workflow';
    case CanonicalWorkspaceRecordViewer = 'canonical_workspace_record_viewer';

    public static function fromRequest(?Request $request = null): self
    {
        if (! $request instanceof Request) {
            return self::WorkspaceScoped;
        }

        return self::fromPath(self::effectivePath($request));
    }

    public static function fromPath(string $path): self
    {
        $normalizedPath = '/'.ltrim($path, '/');

        if ($normalizedPath === '/admin/choose-workspace') {
            return self::WorkspaceChooserException;
        }

        if (preg_match('#^/admin/workspaces/[^/]+/operations/[^/]+$#', $normalizedPath) === 1) {
            return self::CanonicalWorkspaceRecordViewer;
        }

        if (self::isWorkspaceWideSurfacePath($normalizedPath)) {
            return self::WorkspaceWideSurface;
        }

        if (
            str_starts_with($normalizedPath, '/admin/evidence/')
            && ! str_starts_with($normalizedPath, '/admin/evidence/overview')
        ) {
            return self::EnvironmentScopedEvidence;
        }

        if (preg_match('#^/admin/onboarding(?:/[^/]+)?$#', $normalizedPath) === 1) {
            return self::OnboardingWorkflow;
        }

        if (preg_match('#^/admin/workspaces/[^/]+/environments/[^/]+(?:/|$)#', $normalizedPath) === 1) {
            return self::EnvironmentBound;
        }

        return self::WorkspaceScoped;
    }

    public function allowsQueryEnvironmentHints(): bool
    {
        return match ($this) {
            self::WorkspaceWideSurface, self::WorkspaceScoped, self::OnboardingWorkflow => true,
            default => false,
        };
    }

    public function allowsRememberedEnvironmentRestore(): bool
    {
        return match ($this) {
            self::WorkspaceScoped, self::OnboardingWorkflow, self::CanonicalWorkspaceRecordViewer => true,
            default => false,
        };
    }

    public function allowsEnvironmentlessState(): bool
    {
        return match ($this) {
            self::WorkspaceWideSurface,
            self::WorkspaceScoped,
            self::WorkspaceChooserException,
            self::OnboardingWorkflow,
            self::CanonicalWorkspaceRecordViewer => true,
            default => false,
        };
    }

    public function forcesEnvironmentlessShellContext(): bool
    {
        return match ($this) {
            self::WorkspaceWideSurface,
            self::WorkspaceChooserException,
            self::CanonicalWorkspaceRecordViewer => true,
            default => false,
        };
    }

    public function requiresExplicitEnvironment(): bool
    {
        return match ($this) {
            self::EnvironmentBound, self::EnvironmentScopedEvidence => true,
            default => false,
        };
    }

    public function lane(): TenantInteractionLane
    {
        return TenantInteractionLane::fromSurfaceScope($this);
    }

    private static function isWorkspaceWideSurfacePath(string $normalizedPath): bool
    {
        return WorkspaceHubRegistry::isWorkspaceHubPath($normalizedPath);
    }

    private static function effectivePath(Request $request): string
    {
        $path = '/'.ltrim((string) $request->path(), '/');

        if (! self::isLivewireRequestPath($path) && ! $request->headers->has('x-livewire')) {
            return $path;
        }

        $refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH);

        return is_string($refererPath) && $refererPath !== ''
            ? '/'.ltrim($refererPath, '/')
            : $path;
    }

    private static function isLivewireRequestPath(string $path): bool
    {
        return preg_match('#^/(?:livewire(?:-[^/]+)?/update|livewire-unit-test-endpoint)(?:/|$)#', $path) === 1;
    }
}
