<?php
/** /api/auth/* */

function route_auth_login(): void {
    ensure_admin_seed();
    $body = read_json_body();
    $username = strtolower(trim(require_field($body, 'username')));
    $password = require_field($body, 'password');

    $stmt = db()->prepare('SELECT * FROM users WHERE username = ?');
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    if (!$user || !password_verify($password, $user['password_hash'])) {
        json_error(401, 'Invalid username or password');
    }

    $token = make_access_token($user);
    send_json([
        'access_token' => $token,
        'token_type'   => 'bearer',
        'user'         => shape_user($user),
    ]);
}

function route_auth_me(): void {
    $user = require_auth();
    // Re-fetch for freshness — use SELECT * so we never crash on missing columns
    $stmt = db()->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->execute([$user['id']]);
    $fresh = $stmt->fetch();
    send_json(shape_user($fresh ?: $user));
}
