<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\LoginThrottle;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Core\View;

final class AuthController
{
    /** @param array<string,string> $params */
    public function showLogin(Request $request, array $params): Response
    {
        if (Auth::check()) {
            return Response::redirect(base_url('admin'));
        }

        return Response::html(View::render('admin/login', [
            'pageTitle' => 'Connexion',
            'error'     => Session::pull('flash_error'),
        ], 'layouts/admin_minimal'));
    }

    /** @param array<string,string> $params */
    public function login(Request $request, array $params): Response
    {
        $token = $request->input('_csrf');
        if (!Csrf::check(is_string($token) ? $token : null)) {
            return $this->back('Session expirée, merci de réessayer.');
        }

        $throttle = new LoginThrottle();
        if ($throttle->tooManyAttempts()) {
            return $this->back('Trop de tentatives. Réessayez dans ' . $throttle->secondsRemaining() . ' s.');
        }

        $email    = trim((string) $request->input('email', ''));
        $password = (string) $request->input('password', '');

        if ($email !== '' && $password !== '' && Auth::attempt($email, $password)) {
            $throttle->clear();
            return Response::redirect(base_url('admin'));
        }

        $throttle->hit();
        return $this->back('Identifiants invalides.');
    }

    /** @param array<string,string> $params */
    public function logout(Request $request, array $params): Response
    {
        $token = $request->input('_csrf');
        if (Csrf::check(is_string($token) ? $token : null)) {
            Auth::logout();
        }

        return Response::redirect(base_url('admin/login'));
    }

    private function back(string $error): Response
    {
        Session::set('flash_error', $error);
        return Response::redirect(base_url('admin/login'));
    }
}
