<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\UserGroupService;
use Illuminate\Http\Request;

class UserGroupController extends Controller
{
    protected $userGroupService;

    public function __construct(UserGroupService $userGroupService)
    {
        $this->userGroupService = $userGroupService;
    }

    public function index(Request $request)
    {
        $result = $this->userGroupService->index($request->all());

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'code' => 'required|string|max:50|alpha_dash',
            'description' => 'nullable|string|max:255',
            'icon' => 'nullable|string|max:255',
            'color' => 'nullable|string|max:20',
            'is_default' => 'nullable|integer|in:0,1',
            'sort' => 'nullable|integer',
            'status' => 'nullable|integer|in:0,1',
        ]);

        $result = $this->userGroupService->store($validated);

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

    public function show($id)
    {
        $result = $this->userGroupService->show($id);

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

    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'code' => 'required|string|max:50|alpha_dash',
            'description' => 'nullable|string|max:255',
            'icon' => 'nullable|string|max:255',
            'color' => 'nullable|string|max:20',
            'is_default' => 'nullable|integer|in:0,1',
            'sort' => 'nullable|integer',
            'status' => 'nullable|integer|in:0,1',
        ]);

        $result = $this->userGroupService->update($id, $validated);

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

    public function destroy($id)
    {
        $result = $this->userGroupService->destroy($id);

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

    public function all()
    {
        $result = $this->userGroupService->all();

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