<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceSetting;
use App\Services\Auth\WorkspaceCapabilityResolver;
use App\Support\Auth\Capabilities;
use Illuminate\Auth\Access\Response;

class WorkspaceSettingPolicy
{
    public function viewAny(User $user): bool|Response
    {
        return Response::allow();
    }

    public function view(User $user, WorkspaceSetting $workspaceSetting): bool|Response
    {
        return $this->authorizeForWorkspace(
            user: $user,
            workspace: $workspaceSetting->workspace,
            capability: Capabilities::WORKSPACE_SETTINGS_VIEW,
        );
    }

    public function create(User $user): bool|Response
    {
        return Response::deny();
    }

    public function update(User $user, WorkspaceSetting $workspaceSetting): bool|Response
    {
        return $this->authorizeForWorkspace(
            user: $user,
            workspace: $workspaceSetting->workspace,
            capability: Capabilities::WORKSPACE_SETTINGS_MANAGE,
        );
    }

    public function delete(User $user, WorkspaceSetting $workspaceSetting): bool|Response
    {
        return $this->authorizeForWorkspace(
            user: $user,
            workspace: $workspaceSetting->workspace,
            capability: Capabilities::WORKSPACE_SETTINGS_MANAGE,
        );
    }

    public function viewForWorkspace(User $user, Workspace $workspace): bool|Response
    {
        return $this->authorizeForWorkspace(
            user: $user,
            workspace: $workspace,
            capability: Capabilities::WORKSPACE_SETTINGS_VIEW,
        );
    }

    public function manageForWorkspace(User $user, Workspace $workspace): bool|Response
    {
        return $this->authorizeForWorkspace(
            user: $user,
            workspace: $workspace,
            capability: Capabilities::WORKSPACE_SETTINGS_MANAGE,
        );
    }

    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 $resolver->can($user, $workspace, $capability)
            ? Response::allow()
            : Response::deny();
    }
}
