<?php

namespace App\Policies;

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

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

    public function view(User $user, Company $company): bool
    {
        return AccessControl::allows($user, 'companies', 'read');
    }

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

    public function update(User $user, Company $company): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'companies', 'update');
        if ($decision !== null) {
            return $decision;
        }

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

        return AccessControl::isElevated($user) || $company->owner_id === $user->id;
    }

    public function delete(User $user, Company $company): bool
    {
        $decision = AccessControl::overridePermissionState($user, 'companies', 'delete');
        if ($decision !== null) {
            return $decision;
        }

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

        return AccessControl::isElevated($user);
    }
}
