<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use App\Models\User;
use App\Services\UserService;


class CreateUserController extends Controller
{
    public function __construct(protected UserService $userService) {}
    public function createUsers(Request $request): RedirectResponse
    {

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|string|min:8',
            'password_confirm' => 'required|string|min:8'
        ]);

        try {
            $user = $this->userService->createUser($validated);
            return redirect()->route('users.view', ['user' => $user], 200)->with('message', 'Usuário cadastrado com sucesso!');
        } catch (\Exception $e) {
            return redirect()->route('users.create', status: 403)->with('error', $e->getMessage());
        }
    }
}
