<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Repositories\UserRepository;
use App\Support\Auth;
use App\Support\Request;
use App\Support\Response;

final class AuthController
{
    public function login(Request $request): void
    {
        $payload = $request->input();
        $user = (new UserRepository())->findByEmail(trim((string) ($payload['email'] ?? '')));

        if ($user === null || !password_verify((string) ($payload['password'] ?? ''), $user['password_hash'])) {
            Response::json(['message' => 'Ungueltige Zugangsdaten'], 422);
        }

        if (!(int) $user['is_active'] || ((int) ($user['tenant_is_active'] ?? 1) !== 1 && $user['role'] !== 'superadmin')) {
            Response::json(['message' => 'Benutzer oder Mandant ist deaktiviert'], 403);
        }

        $_SESSION['user_id'] = (int) $user['id'];

        Response::json(['user' => $this->sanitizeUser($user)]);
    }

    public function logout(): void
    {
        session_destroy();
        Response::noContent();
    }

    public function me(): void
    {
        $user = Auth::user();
        Response::json(['user' => $user ? $this->sanitizeUser($user) : null]);
    }

    private function sanitizeUser(array $user): array
    {
        unset($user['password_hash']);
        return $user;
    }
}
