<?php

namespace App\Http\Controllers\Superadmin;

use App\DTOs\Auth\RegisterDTO;
use App\DTOs\Auth\UpdateUserDTO;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\RegisterRequest;
use App\Http\Requests\Auth\UpdateUserRequest;
use App\Services\AuthService;
use App\Services\UserService;
use Illuminate\View\View;

class UserController extends Controller
{
    public function __construct(protected UserService $userService, protected AuthService $authService)
    {
    }

    public function index(): View
    {
        $users = $this->userService->getUserByRole("admin");
        return view('superadmin.users.index', compact('users'));
    }

    public function create(): View
    {
        return view('superadmin.users.create');
    }

    public function store(RegisterRequest $request)
    {
        $dto = RegisterDTO::fromRequest($request);
        $userNew = $this->authService->register($dto);
        if ($userNew) {
            return redirect()->route('superadmin.users.index')->with('success', 'Usuario creado correctamente.');
        }
        return back()->with('error', 'No se pudo guardar el usuario.')->withInput();
    }
        

    public function show($id): View
    {
        $user = $this->userService->getUserById($id);
        if (!$user) {
            abort(404);
        }
        return view('superadmin.users.show', compact('user'));
    }

    public function edit($id): View
    {
        $user = $this->userService->getUserById($id);
        if (!$user) {
            abort(404);
        }
        return view('superadmin.users.edit', compact('user'));
    }

    public function update(UpdateUserRequest $request, $id)
    {
        $dto = UpdateUserDTO::fromRequest($request);

        $user = $this->authService->update($id, $dto);
        
        if ($user) {
            return redirect()->route('superadmin.users.index')->with('success', 'Usuario actualizado correctamente.');
        }
        return back()->with('error', 'No se pudo actualizar el usuario.')->withInput();
    }

    public function destroy($id)
    {
        $deleted = $this->userService->delete($id);
        if ($deleted) {
            return redirect()->route('superadmin.users.index')->with('success', 'Usuario eliminado correctamente.');
        }
        return redirect()->route('superadmin.users.index')->with('error', 'No se pudo eliminar el usuario.');
    }
}