<?php

declare(strict_types=1);

namespace App\Support\Tenants;

use Illuminate\Http\Request;

enum TenantPageCategory: string
{
    case WorkspaceScoped = 'workspace_scoped';
    case WorkspaceChooserException = 'workspace_chooser_exception';
    case TenantBound = 'tenant_bound';
    case TenantScopedEvidence = 'tenant_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('/'.ltrim($request->path(), '/'));
    }

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

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

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

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

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

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

        return self::WorkspaceScoped;
    }

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

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

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

    public function requiresExplicitTenant(): bool
    {
        return match ($this) {
            self::TenantBound, self::TenantScopedEvidence => true,
            default => false,
        };
    }

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