<?php

namespace App\Policies;

use App\Models\Finding;
use App\Models\Tenant;
use App\Models\User;
use App\Support\TenantRole;
use Illuminate\Auth\Access\HandlesAuthorization;

class FindingPolicy
{
    use HandlesAuthorization;

    public function viewAny(User $user): bool
    {
        $tenant = Tenant::current();

        if (! $tenant) {
            return false;
        }

        return $user->canAccessTenant($tenant);
    }

    public function view(User $user, Finding $finding): bool
    {
        $tenant = Tenant::current();

        if (! $tenant) {
            return false;
        }

        if (! $user->canAccessTenant($tenant)) {
            return false;
        }

        return (int) $finding->tenant_id === (int) $tenant->getKey();
    }

    public function update(User $user, Finding $finding): bool
    {
        $tenant = Tenant::current();

        if (! $tenant) {
            return false;
        }

        if (! $user->canAccessTenant($tenant)) {
            return false;
        }

        if ((int) $finding->tenant_id !== (int) $tenant->getKey()) {
            return false;
        }

        $role = $user->tenantRole($tenant);

        return match ($role) {
            TenantRole::Owner,
            TenantRole::Manager,
            TenantRole::Operator => true,
            default => false,
        };
    }
}
