<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Models\AuditLog;
use App\Models\LoginAttempt;
use App\Models\User;

final class AuthController extends BaseController
{
    public function showLogin(Request $request): void
    {
        if (Auth::instance()->check()) {
            redirect('dashboard');
        }
        view('auth/login', ['title' => 'Sign in', 'error' => flash('error')], 'layouts/auth');
    }

    public function login(Request $request): void
    {
        $this->verifyCsrf($request);
        $email = strtolower((string) $request->input('email', ''));
        $password = (string) ($_POST['password'] ?? '');
        $ip = request_ip();
        $max = (int) config('security.login_max_attempts', 8);
        $window = (int) config('security.login_window_minutes', 15);

        if ($email === '' || $password === '') {
            flash('error', 'Enter your email and password.');
            redirect('login');
        }
        if (LoginAttempt::tooMany($email, $ip, $max, $window)) {
            flash('error', 'Too many sign-in tries. Wait a few minutes.');
            redirect('login');
        }

        $user = User::findByEmail($email);
        $ok = $user && $user['status'] === 'active' && password_verify($password, $user['password_hash']);
        LoginAttempt::record($email, $ip, $ok);
        if (!$ok) {
            flash('error', 'Email or password is not correct.');
            redirect('login');
        }

        $tenants = User::tenants((int) $user['id']);
        if ($tenants === []) {
            flash('error', 'Your login is not linked to a company.');
            redirect('login');
        }

        User::markLogin((int) $user['id']);
        $tenant = $tenants[0];
        $roles = User::rolesFor((int) $user['id'], (int) $tenant['id']);
        Auth::instance()->login($user, $tenant, $roles);
        AuditLog::write('auth.login', 'user', (int) $user['id']);
        redirect('dashboard');
    }

    public function logout(Request $request): void
    {
        if (Auth::instance()->check()) {
            AuditLog::write('auth.logout', 'user', Auth::instance()->id());
        }
        Auth::instance()->logout();
        redirect('login');
    }
}
