<?php

namespace App\Policies;

use App\Models\Solicitor\Solicitor;
use App\Models\User\User;
use App\Models\Witness\WitnessStatement;

class WitnessStatementPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->can('clients.witness.view');
    }

    public function view(User $user, WitnessStatement $statement): bool
    {
        return $user->can('clients.witness.view')
            && $this->inActiveTenant($user, $statement);
    }

    public function update(User $user, WitnessStatement $statement): bool
    {
        return $user->can('clients.witness.edit')
            && $this->inActiveTenant($user, $statement)
            && ! $statement->isApproved();
    }

    public function generate(User $user, WitnessStatement $statement): bool
    {
        return $user->can('clients.witness.generate')
            && $this->inActiveTenant($user, $statement);
    }

    public function approve(User $user, WitnessStatement $statement): bool
    {
        return $user->can('clients.witness.approve')
            && $this->inActiveTenant($user, $statement);
    }

    /**
     * Defence in depth on top of the BelongsToSolicitor global scope.
     *
     * The tenant boundary is the RESOLVED workspace (App\Models\Solicitor\Solicitor
     * bound into the container by SetSolicitorFromDomain — from the subdomain or the
     * selected workspace_solicitor_id). This is deliberately NOT the user's own
     * solicitor_id column: platform users have a null solicitor_id yet legitimately
     * operate inside a workspace they have switched into, and a per-user check would
     * wrongly lock them out. When no workspace is resolved we fall back to the user's
     * own solicitor so a solicitor-scoped user is still constrained.
     */
    private function inActiveTenant(User $user, WitnessStatement $statement): bool
    {
        $tenant = app()->bound(Solicitor::class) ? app(Solicitor::class) : null;

        if ($tenant && $tenant->id) {
            return (int) $tenant->id === (int) $statement->solicitor_id;
        }

        return $user->solicitor_id !== null
            && (int) $user->solicitor_id === (int) $statement->solicitor_id;
    }
}
