<?php

namespace App\Http\Controllers;

use App\Models\Group;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;

class GroupController extends Controller
{
    public function index(): Response
    {
        $groups = Group::withCount('users')->orderBy('name')->get();

        return Inertia::render('groups/Index', [
            'groups' => $groups,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:40', Rule::unique('groups', 'name')],
            'description' => ['nullable', 'string', 'max:255'],
        ]);

        Group::create($data);

        Inertia::flash('toast', ['type' => 'success', 'message' => __('Grup berhasil dibuat.')]);

        return to_route('groups.index');
    }

    public function update(Request $request, Group $group): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:40', Rule::unique('groups', 'name')->ignore($group->id)],
            'description' => ['nullable', 'string', 'max:255'],
        ]);

        $group->update($data);

        Inertia::flash('toast', ['type' => 'success', 'message' => __('Grup berhasil diperbarui.')]);

        return to_route('groups.index');
    }

    public function destroy(Group $group): RedirectResponse
    {
        // Lindungi grup inti sistem.
        if (in_array($group->name, [Group::ADMIN, Group::MEMBERS, Group::DEVELOPER], true)) {
            Inertia::flash('toast', ['type' => 'error', 'message' => __('Grup inti tidak dapat dihapus.')]);

            return to_route('groups.index');
        }

        $group->delete();

        Inertia::flash('toast', ['type' => 'success', 'message' => __('Grup berhasil dihapus.')]);

        return to_route('groups.index');
    }
}
