<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\ManagedEnvironment;
use App\Models\ManagedEnvironmentOnboardingSession;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Auth\WorkspaceCapabilityResolver;
use App\Services\Tenants\TenantOperabilityService;
use App\Support\Auth\Capabilities;
use App\Support\Tenants\TenantInteractionLane;
use App\Support\Tenants\TenantOperabilityQuestion;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Auth\Access\Response;
use Illuminate\Support\Facades\Gate;

class ManagedEnvironmentOnboardingSessionPolicy
{
    public function viewAny(User $user): bool|Response
    {
        $workspace = $this->currentWorkspace($user);

        if (! $workspace instanceof Workspace) {
            return Response::denyAsNotFound();
        }

        return $this->authorizeForWorkspace($user, $workspace, Capabilities::WORKSPACE_MANAGED_ENVIRONMENT_ONBOARD);
    }

    public function view(User $user, ManagedEnvironmentOnboardingSession $environmentOnboardingSession): bool|Response
    {
        return $this->authorizeForDraft(
            user: $user,
            environmentOnboardingSession: $environmentOnboardingSession,
            capability: Capabilities::WORKSPACE_MANAGED_ENVIRONMENT_ONBOARD,
        );
    }

    public function update(User $user, ManagedEnvironmentOnboardingSession $environmentOnboardingSession): bool|Response
    {
        return $this->authorizeForDraft(
            user: $user,
            environmentOnboardingSession: $environmentOnboardingSession,
            capability: Capabilities::WORKSPACE_MANAGED_ENVIRONMENT_ONBOARD,
        );
    }

    public function cancel(User $user, ManagedEnvironmentOnboardingSession $environmentOnboardingSession): bool|Response
    {
        return $this->authorizeForDraft(
            user: $user,
            environmentOnboardingSession: $environmentOnboardingSession,
            capability: Capabilities::WORKSPACE_MANAGED_ENVIRONMENT_ONBOARD_CANCEL,
        );
    }

    private function currentWorkspace(User $user): ?Workspace
    {
        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());

        if (! is_int($workspaceId)) {
            return null;
        }

        $workspace = Workspace::query()->whereKey($workspaceId)->first();

        if (! $workspace instanceof Workspace) {
            return null;
        }

        /** @var WorkspaceCapabilityResolver $resolver */
        $resolver = app(WorkspaceCapabilityResolver::class);

        if (! $resolver->isMember($user, $workspace)) {
            return null;
        }

        return $workspace;
    }

    private function authorizeForDraft(
        User $user,
        ManagedEnvironmentOnboardingSession $environmentOnboardingSession,
        string $capability,
    ): bool|Response {
        $workspace = $this->currentWorkspace($user);

        if (! $workspace instanceof Workspace) {
            return Response::denyAsNotFound();
        }

        if ((int) $environmentOnboardingSession->workspace_id !== (int) $workspace->getKey()) {
            return Response::denyAsNotFound();
        }

        $tenant = $environmentOnboardingSession->managedEnvironment;

        if ($tenant instanceof ManagedEnvironment) {
            if ((int) $tenant->workspace_id !== (int) $workspace->getKey()) {
                return Response::denyAsNotFound();
            }

            if (! $user->canAccessTenant($tenant)) {
                return Response::denyAsNotFound();
            }

            $viewability = app(TenantOperabilityService::class)->outcomeFor(
                tenant: $tenant,
                question: TenantOperabilityQuestion::EnvironmentBoundViewability,
                actor: $user,
                workspaceId: (int) $workspace->getKey(),
                lane: TenantInteractionLane::AdministrativeManagement,
            );

            if (! $viewability->allowed) {
                return Response::denyAsNotFound();
            }
        }

        return $this->authorizeForWorkspace($user, $workspace, $capability);
    }

    private function authorizeForWorkspace(User $user, Workspace $workspace, string $capability): bool|Response
    {
        /** @var WorkspaceCapabilityResolver $resolver */
        $resolver = app(WorkspaceCapabilityResolver::class);

        if (! $resolver->isMember($user, $workspace)) {
            return Response::denyAsNotFound();
        }

        return Gate::forUser($user)->allows($capability, $workspace)
            ? Response::allow()
            : Response::deny($this->forbiddenCapabilityMessage($capability));
    }

    private function forbiddenCapabilityMessage(string $capability): string
    {
        return match ($capability) {
            Capabilities::WORKSPACE_MANAGED_ENVIRONMENT_ONBOARD_CANCEL => 'You do not have permission to cancel this onboarding draft.',
            default => 'You do not have permission to continue this onboarding draft.',
        };
    }
}
