<?php

namespace App\Http\Controllers;

use App\Services\Auth\Contracts\AuthServiceInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function __construct(
        private AuthServiceInterface $authService
    ) {}

    public function showLoginForm()
    {
        if (Auth::check()) {
            return redirect($this->authService->getRedirectRouteForUser(Auth::user()));
        }
        return view('login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'mail'     => 'required|email|max:255',
            'password' => 'required|string|max:100',
        ]);

        $result = $this->authService->attemptLogin($credentials, $request);

        if (!$result['success']) {
            return back()->withInput($request->only('mail'))->withErrors([
                $result['error_key'] => $result['error_msg'],
            ]);
        }

        return redirect($this->authService->getRedirectRouteForUser($result['user']));
    }

    public function logout(Request $request)
    {
        $this->authService->logout($request);
        return redirect('/login');
    }
}
