<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class UserController extends Controller
{
    /**
     * Display a listing of the users.
     */
    public function index(Request $request): Response
    {
        $perPage = min(max((int) $request->input('per_page', 10), 10), 100);

        $users = User::query()
            ->latest()
            ->paginate($perPage)
            ->through(fn (User $user) => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'group' => $user->group->value,
                'created_at' => $user->created_at?->toISOString(),
                'editUrl' => route('users.edit', $user),
                'destroyUrl' => route('users.destroy', $user),
            ]);

        return Inertia::render('users/Index', [
            'users' => $users,
            'createUrl' => route('users.create'),
        ]);
    }

    /**
     * Show the form for creating a new user.
     */
    public function create(): Response
    {
        return Inertia::render('users/Create', [
            'indexUrl' => route('users.index'),
            'storeUrl' => route('users.store'),
            'userGroups' => \App\Enums\UserGroup::asSelectArray(),
        ]);
    }

    /**
     * Store a newly created user in storage.
     */
    public function store(StoreUserRequest $request): RedirectResponse
    {
        User::query()->create($request->validated());

        return to_route('users.index');
    }

    /**
     * Show the form for editing the specified user.
     */
    public function edit(User $user): Response
    {
        return Inertia::render('users/Edit', [
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'group' => $user->group->value,
            ],
            'indexUrl' => route('users.index'),
            'updateUrl' => route('users.update', $user),
            'userGroups' => \App\Enums\UserGroup::asSelectArray(),
        ]);
    }

    /**
     * Update the specified user in storage.
     */
    public function update(UpdateUserRequest $request, User $user): RedirectResponse
    {
        $data = $request->validated();

        if (empty($data['password'])) {
            unset($data['password']);
            unset($data['password_confirmation']);
        }

        $user->update($data);

        return to_route('users.index');
    }

    /**
     * Remove the specified user from storage.
     */
    public function destroy(User $user): RedirectResponse
    {
        $user->delete();

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