<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Database;
use App\Core\Jwt;
use App\Core\Request;
use App\Core\Response;

final class AuthController
{
    public function login(): void
    {
        $data = Request::json();
        $stmt = Database::connection()->prepare('SELECT * FROM users WHERE email = :email AND active = 1');
        $stmt->execute(['email' => $data['email'] ?? '']);
        $user = $stmt->fetch();

        if (!$user || !password_verify($data['password'] ?? '', $user['password_hash'])) {
            Response::error('Credenciales inválidas', 422);
            return;
        }

        $token = Jwt::encode([
            'sub' => (int) $user['id'],
            'name' => $user['name'],
            'email' => $user['email'],
            'role' => $user['role'],
        ]);

        Response::json(['token' => $token, 'user' => ['name' => $user['name'], 'email' => $user['email'], 'role' => $user['role']]]);
    }

    public function me(): void
    {
        $user = Auth::requireRole(['admin', 'delegate', 'public']);
        Response::json(['user' => [
            'name' => $user['name'],
            'email' => $user['email'],
            'role' => $user['role'],
        ]]);
    }
}
