<?php

require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/database.php';

function requireAuth(): array
{
    $config = require __DIR__ . '/../config/app.php';
    global $pdo;

    $token = getRequestToken($config);
    if (!$token) {
        jsonResponse(false, 'Unauthorized', null, 401);
    }

    $tokenHash = hashToken($token);

    $sql = "
        SELECT
            us.id AS session_id,
            us.user_id,
            us.expires_at,
            us.is_revoked,
            u.id,
            u.name,
            u.username,
            u.email,
            u.phone,
            u.avatar,
            u.country,
            u.agent,
            u.ip,
            u.is_active,
            u.role,
            u.created_at,
            u.updated_at
        FROM user_sessions us
        INNER JOIN users u ON u.id = us.user_id
        WHERE us.token_hash = :token_hash
        LIMIT 1
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute(['token_hash' => $tokenHash]);
    $user = $stmt->fetch();

    if (!$user) {
        jsonResponse(false, 'Invalid session', null, 401);
    }

    if ((int)$user['is_revoked'] === 1) {
        jsonResponse(false, 'Session revoked', null, 401);
    }

    if (strtotime((string)$user['expires_at']) < time()) {
        jsonResponse(false, 'Session expired', null, 401);
    }

    if ((int)$user['is_active'] !== 1) {
        jsonResponse(false, 'User is inactive', null, 403);
    }

    $touch = $pdo->prepare('UPDATE user_sessions SET last_seen_at = NOW() WHERE id = :id');
    $touch->execute(['id' => $user['session_id']]);

    return sanitizeUser($user);
}
