<?php

namespace App\Http\Controllers\Admin\System;

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

class MenuController extends Controller
{
    /**
     * 菜单树
     */
    public function index(): JsonResponse
    {
        return $this->success(Menu::tree());
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'parent_id' => 'nullable|integer',
            'name' => 'required|string|max:50',
            'path' => 'nullable|string|max:255',
            'component' => 'nullable|string|max:255',
            'icon' => 'nullable|string|max:50',
            'permission_code' => 'nullable|string|max:100',
            'type' => 'required|in:1,2,3',
            'visible' => 'in:0,1',
            'sort' => 'nullable|integer',
            'status' => 'in:0,1',
        ]);

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

    public function update(Request $request, Menu $menu): JsonResponse
    {
        $data = $request->validate([
            'parent_id' => 'nullable|integer',
            'name' => 'string|max:50',
            'path' => 'nullable|string|max:255',
            'component' => 'nullable|string|max:255',
            'icon' => 'nullable|string|max:50',
            'permission_code' => 'nullable|string|max:100',
            'type' => 'in:1,2,3',
            'visible' => 'in:0,1',
            'sort' => 'nullable|integer',
            'status' => 'in:0,1',
        ]);

        if (isset($data['parent_id']) && $data['parent_id'] == $menu->id) {
            return $this->error('不能设置自身为上级菜单');
        }

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

    public function destroy(Menu $menu): JsonResponse
    {
        if ($menu->children()->exists()) {
            return $this->error('该菜单下还有子菜单，无法删除');
        }

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