<?php

namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Authz\RolePermissionGrantRequest;
use App\Http\Requests\Authz\RolePermissionToggleRequest;
use App\Services\Authz\RolePermissionService;

class RolePermissionController extends Controller
{
    public function index($id)
    {
        return ApiResponse::handle(function () use ($id) {
            return RolePermissionService::list((int) $id);
        }, __('message.fetched'));
    }

    public function grant($id, RolePermissionGrantRequest $request)
    {
        return ApiResponse::handle(function () use ($id, $request) {
            return RolePermissionService::grant((int) $id, $request->validated());
        }, __('message.updated'));
    }

    public function revoke($id, RolePermissionGrantRequest $request)
    {
        return ApiResponse::handle(function () use ($id, $request) {
            return RolePermissionService::revoke((int) $id, $request->validated());
        }, __('message.updated'));
    }

    public function sync($id, RolePermissionGrantRequest $request)
    {
        return ApiResponse::handle(function () use ($id, $request) {
            return RolePermissionService::sync((int) $id, $request->validated());
        }, __('message.updated'));
    }

    /**
     * 권한 매트릭스용 메뉴 트리 조회
     */
    public function menus()
    {
        return ApiResponse::handle(function () {
            return RolePermissionService::menus();
        }, __('message.fetched'));
    }

    /**
     * 역할의 권한 매트릭스 조회
     */
    public function matrix($id)
    {
        return ApiResponse::handle(function () use ($id) {
            return RolePermissionService::matrix((int) $id);
        }, __('message.fetched'));
    }

    /**
     * 특정 메뉴의 특정 권한 토글
     */
    public function toggle($id, RolePermissionToggleRequest $request)
    {
        return ApiResponse::handle(function () use ($id, $request) {
            return RolePermissionService::toggle((int) $id, $request->validated());
        }, __('message.updated'));
    }

    /**
     * 모든 권한 허용
     */
    public function allowAll($id)
    {
        return ApiResponse::handle(function () use ($id) {
            return RolePermissionService::allowAll((int) $id);
        }, __('message.updated'));
    }

    /**
     * 모든 권한 거부
     */
    public function denyAll($id)
    {
        return ApiResponse::handle(function () use ($id) {
            return RolePermissionService::denyAll((int) $id);
        }, __('message.updated'));
    }

    /**
     * 기본 권한으로 초기화 (view만 허용)
     */
    public function reset($id)
    {
        return ApiResponse::handle(function () use ($id) {
            return RolePermissionService::reset((int) $id);
        }, __('message.updated'));
    }
}
