<?php
declare(strict_types=1);

namespace App\Modules\Auth;

use App\Core\Http\Request;
use App\Core\Http\Response;
use App\Core\I18n\Translator;
use App\Core\Security\Csrf;
use App\Core\Support\Flash;
use App\Core\View\Template;

final class AuthController
{
    public function __construct(
        private readonly Template $template,
        private readonly AuthService $auth,
        private readonly Translator $translator
    ) {
    }

    public function showLogin(Request $request): Response
    {
        if ($this->auth->check()) {
            return Response::redirect('/settings/users');
        }

        $html = $this->template->render('auth/login', [
            'title' => $this->translator->get('auth.login.title'),
            'errorMessage' => Flash::get('error'),
            'oldEmail' => (string) Flash::get('old_email', ''),
            'csrfToken' => Csrf::token(),
        ], 'layouts/auth');

        return Response::html($html);
    }

    public function login(Request $request): Response
    {
        $csrfToken = (string) $request->input('_token', '');
        if (!Csrf::validate($csrfToken)) {
            Flash::set('error', $this->translator->get('auth.errors.csrf_expired'));
            Flash::set('old_email', (string) $request->input('email', ''));
            return Response::redirect('/login');
        }

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

        if (!filter_var($email, FILTER_VALIDATE_EMAIL) || $password === '') {
            Flash::set('error', $this->translator->get('auth.errors.invalid_credentials_format'));
            Flash::set('old_email', $email);
            return Response::redirect('/login');
        }

        if (!$this->auth->attempt($email, $password)) {
            Flash::set('error', $this->translator->get('auth.errors.invalid_credentials'));
            Flash::set('old_email', $email);
            return Response::redirect('/login');
        }

        return Response::redirect('/settings/users');
    }

    public function logout(Request $request): Response
    {
        $csrfToken = (string) $request->input('_token', '');
        if (!Csrf::validate($csrfToken)) {
            Flash::set('error', $this->translator->get('auth.errors.csrf_expired'));
            return Response::redirect('/login');
        }

        $this->auth->logout();
        return Response::redirect('/login');
    }
}
