<?php

namespace App\Http\Controllers\Auth;

use App\DTOs\Auth\LoginDTO;
use App\DTOs\Auth\RegisterDTO;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Requests\Auth\RegisterRequest;
use App\Providers\RouteServiceProvider;
use App\Services\AuthService;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function __construct(protected AuthService $authService) {}

    public function showLogin()
    {
        return view('auth.login');
    }

    public function login(LoginRequest $request)
    {
        $dto = LoginDTO::fromRequest($request);

        if ($this->authService->attemptLogin($dto)) {
            $request->session()->regenerate();

            $redirectTo = RouteServiceProvider::redirectTo();
            return redirect($redirectTo);
        }

        return back()->withErrors(['email' => 'Las credenciales no son válidas.']);
    }

    public function showRegister()
    {
        return view('auth.register');
    }


    public function logout(Request $request)
    {
        $this->authService->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login');
    }
}
