<?php

namespace App\Policies;

use App\Models\Tenant;
use App\Models\User;

/**
 * First policy in the app (Team Workspaces P3, Δ22/Δ24). Splits workspace
 * abilities into two tiers:
 *
 *   - owner-OR-admin: invite / revoke / remove editor-or-viewer / change
 *     editor↔viewer role / rename / share-or-revoke a project.
 *   - owner-ONLY: set/remove the Admin role, touch billing. (Ownership
 *     transfer + workspace delete were descoped — single-personal-workspace.)
 *
 * Registered against the `Tenant` model in `bootstrap/app.php` via
 * `Gate::policy()` (auto-discovery maps Tenant → TenantPolicy, which doesn't
 * exist; explicit registration keeps the name aligned with the feature).
 * Every method takes the acting User + the target Tenant.
 *
 * Self-hosted has no pivot/policy surface — user/role administration is the
 * existing `is_admin`-gated `/admin/users` flow (Δ22). These abilities are
 * only reachable from the SaaS `/workspace/*` routes.
 */
class WorkspacePolicy
{
    // -- owner-or-admin abilities ------------------------------------------

    public function invite(User $user, Tenant $tenant): bool
    {
        return $this->isOwnerOrAdmin($user, $tenant);
    }

    public function revokeInvite(User $user, Tenant $tenant): bool
    {
        return $this->isOwnerOrAdmin($user, $tenant);
    }

    public function removeEditorOrViewer(User $user, Tenant $tenant): bool
    {
        return $this->isOwnerOrAdmin($user, $tenant);
    }

    public function changeEditorViewerRole(User $user, Tenant $tenant): bool
    {
        return $this->isOwnerOrAdmin($user, $tenant);
    }

    public function rename(User $user, Tenant $tenant): bool
    {
        return $this->isOwnerOrAdmin($user, $tenant);
    }

    public function shareProject(User $user, Tenant $tenant): bool
    {
        return $this->isOwnerOrAdmin($user, $tenant);
    }

    public function revokeProjectShare(User $user, Tenant $tenant): bool
    {
        return $this->isOwnerOrAdmin($user, $tenant);
    }

    // -- owner-only abilities ----------------------------------------------

    public function setAdminRole(User $user, Tenant $tenant): bool
    {
        return $user->isOwnerOf($tenant);
    }

    public function removeAdmin(User $user, Tenant $tenant): bool
    {
        return $user->isOwnerOf($tenant);
    }

    private function isOwnerOrAdmin(User $user, Tenant $tenant): bool
    {
        return in_array($user->roleIn($tenant), ['owner', 'admin'], true);
    }
}
