<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\Tenant;
use App\Models\TenantOnboardingSession;
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 TenantOnboardingSessionPolicy
{
    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_TENANT_ONBOARD);
    }

    public function view(User $user, TenantOnboardingSession $tenantOnboardingSession): bool|Response
    {
        return $this->authorizeForDraft(
            user: $user,
            tenantOnboardingSession: $tenantOnboardingSession,
            capability: Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD,
        );
    }

    public function update(User $user, TenantOnboardingSession $tenantOnboardingSession): bool|Response
    {
        return $this->authorizeForDraft(
            user: $user,
            tenantOnboardingSession: $tenantOnboardingSession,
            capability: Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD,
        );
    }

    public function cancel(User $user, TenantOnboardingSession $tenantOnboardingSession): bool|Response
    {
        return $this->authorizeForDraft(
            user: $user,
            tenantOnboardingSession: $tenantOnboardingSession,
            capability: Capabilities::WORKSPACE_MANAGED_TENANT_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,
        TenantOnboardingSession $tenantOnboardingSession,
        string $capability,
    ): bool|Response {
        $workspace = $this->currentWorkspace($user);

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

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

        $tenant = $tenantOnboardingSession->tenant;

        if ($tenant instanceof Tenant) {
            $viewability = app(TenantOperabilityService::class)->outcomeFor(
                tenant: $tenant,
                question: TenantOperabilityQuestion::TenantBoundViewability,
                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_TENANT_ONBOARD_CANCEL => 'You do not have permission to cancel this onboarding draft.',
            default => 'You do not have permission to continue this onboarding draft.',
        };
    }
}
