<?php

namespace App\Domains\Menu\Controllers;

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

class MenuController extends Controller
{
    public function index(): JsonResponse
    {
        $menues = Menu::all();

        return response()->json($menues);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'code' => 'required|string|unique:menues,code',
            'label' => 'required|string|max:255',
            'parent_menu_code' => [
                'nullable',
                'string',
                Rule::exists('menues', 'code'),
                'different:code',
            ],
            'content_type' => [
                'sometimes',
                Rule::in([Menu::CONTENT_TYPE_STATIC, Menu::CONTENT_TYPE_DYNAMIC]),
            ],
            'static_content_schema' => 'required_if:content_type,static|nullable|array',
            'route' => 'required|string',
        ]);

        $menu = Menu::create($validated);

        return response()->json($menu, 201);
    }

    public function show(Menu $menu): JsonResponse
    {
        return response()->json($menu);
    }

    public function update(Request $request, Menu $menu): JsonResponse
    {
        $validated = $request->validate([
            'code' => 'sometimes|required|string|unique:menues,code,'.$menu->id,
            'label' => 'sometimes|required|string|max:255',
            'parent_menu_code' => [
                'nullable',
                'string',
                Rule::exists('menues', 'code'),
                Rule::notIn([$menu->code]),
            ],
            'content_type' => [
                'sometimes',
                Rule::in([Menu::CONTENT_TYPE_STATIC, Menu::CONTENT_TYPE_DYNAMIC]),
            ],
            'static_content_schema' => 'required_if:content_type,static|nullable|array',
            'route' => 'sometimes|required|string',
        ]);

        $menu->update($validated);

        return response()->json($menu);
    }

    public function destroy(Menu $menu): JsonResponse
    {
        $menu->delete();

        return response()->json(null, 204);
    }
}
