<?php

namespace App\Policies;

use App\Models\OneCExchange;
use App\Models\User;
use App\Support\AccessControl;

class OneCExchangePolicy
{
    public function viewAny(User $user): bool
    {
        return AccessControl::allows($user, 'onec', 'read');
    }

    public function view(User $user, OneCExchange $exchange): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'onec', 'read');
        if ($decision !== null) {
            return $decision;
        }

        if (! AccessControl::roleAllows($user, 'onec', 'read')) {
            return false;
        }

        return AccessControl::isElevated($user) || $exchange->initiated_by_user_id === $user->id;
    }

    public function create(User $user): bool
    {
        return AccessControl::allows($user, 'onec', 'create');
    }

    public function update(User $user, OneCExchange $exchange): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'onec', 'update');
        if ($decision !== null) {
            return $decision;
        }

        if (! AccessControl::roleAllows($user, 'onec', 'update')) {
            return false;
        }

        return AccessControl::isElevated($user) || $exchange->initiated_by_user_id === $user->id;
    }

    public function delete(User $user, OneCExchange $exchange): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'onec', 'delete');
        if ($decision !== null) {
            return $decision;
        }

        if (! AccessControl::roleAllows($user, 'onec', 'delete')) {
            return false;
        }

        return AccessControl::isElevated($user) || $exchange->initiated_by_user_id === $user->id;
    }
}

