<?php

declare(strict_types=1);

namespace Kylin\Rbac\Policies;

use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * CRUD 权限策略
 *
 * 为资源型控制器提供标准 CRUD 权限校验。
 * 继承此类后，自动实现 viewAny/view/viewCreate/create/update/delete 方法。
 *
 * 使用方式：
 *   class UserPolicy extends CrudPolicy
 *   {
 *       protected string $resource = 'user';
 *   }
 *
 * 权限命名规范：{resource}.{action}，如 user.view、user.create、user.update、user.delete
 */
class CrudPolicy extends BasePolicy
{
    /** 资源名称，子类需覆盖 */
    protected string $resource = '';

    /**
     * 列表查看权限：{resource}.view
     */
    public function viewAny(Authenticatable $user): bool
    {
        return $this->isSuperAdmin($user) || $this->checkPermission($user, "{$this->resource}.view");
    }

    /**
     * 详情查看权限：{resource}.view
     */
    public function view(Authenticatable $user, $model = null): bool
    {
        return $this->isSuperAdmin($user) || $this->checkPermission($user, "{$this->resource}.view");
    }

    /**
     * 创建权限：{resource}.create
     */
    public function create(Authenticatable $user): bool
    {
        return $this->isSuperAdmin($user) || $this->checkPermission($user, "{$this->resource}.create");
    }

    /**
     * 更新权限：{resource}.update
     */
    public function update(Authenticatable $user, $model = null): bool
    {
        return $this->isSuperAdmin($user) || $this->checkPermission($user, "{$this->resource}.update");
    }

    /**
     * 删除权限：{resource}.delete
     */
    public function delete(Authenticatable $user, $model = null): bool
    {
        return $this->isSuperAdmin($user) || $this->checkPermission($user, "{$this->resource}.delete");
    }

    /**
     * 恢复权限：{resource}.restore
     */
    public function restore(Authenticatable $user, $model = null): bool
    {
        return $this->isSuperAdmin($user) || $this->checkPermission($user, "{$this->resource}.restore");
    }

    /**
     * 强制删除权限：{resource}.force-delete
     */
    public function forceDelete(Authenticatable $user, $model = null): bool
    {
        return $this->isSuperAdmin($user) || $this->checkPermission($user, "{$this->resource}.force-delete");
    }
}