<?php

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Controller;
use App\Models\Permission;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PermissionController extends Controller
{
    /**
     * 权限树
     */
    public function index(): JsonResponse
    {
        return $this->success(Permission::tree());
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'parent_id' => 'nullable|integer',
            'name' => 'required|string|max:50',
            'code' => 'required|string|max:100|unique:permissions,code',
            'module' => 'nullable|string|max:50',
            'type' => 'required|in:1,2,3',
            'description' => 'nullable|string|max:255',
            'sort' => 'nullable|integer',
        ]);

        $data['parent_id'] = $data['parent_id'] ?? 0;
        $data['sort'] = $data['sort'] ?? 0;
        $permission = Permission::create($data);
        return $this->success($permission, '创建成功');
    }

    public function update(Request $request, Permission $permission): JsonResponse
    {
        $data = $request->validate([
            'parent_id' => 'nullable|integer',
            'name' => 'string|max:50',
            'code' => 'string|max:100|unique:permissions,code,' . $permission->id,
            'module' => 'nullable|string|max:50',
            'type' => 'in:1,2,3',
            'description' => 'nullable|string|max:255',
            'sort' => 'nullable|integer',
        ]);

        $permission->update($data);
        return $this->success($permission, '更新成功');
    }

    public function destroy(Permission $permission): JsonResponse
    {
        if ($permission->children()->exists()) {
            return $this->error('该权限下有子权限，无法删除');
        }

        $permission->roles()->detach();
        $permission->delete();
        return $this->success(null, '删除成功');
    }
}
