<?php
// server/test_auth_flow.php
require_once 'mail.php'; // Avoid include errors

// Mock functions from auth.php
$file = 'data/users.json';
function getU()
{
    global $file;
    return json_decode(file_get_contents($file), true) ?? [];
}

function runAuth($payload)
{
    $descriptorSpec = [
        0 => ["pipe", "r"],
        1 => ["pipe", "w"],
        2 => ["pipe", "w"]
    ];
    $process = proc_open('php auth.php', $descriptorSpec, $pipes);
    if (is_resource($process)) {
        fwrite($pipes[0], json_encode($payload));
        fclose($pipes[0]);

        $out = stream_get_contents($pipes[1]);
        fclose($pipes[1]);

        $err = stream_get_contents($pipes[2]);
        fclose($pipes[2]);

        proc_close($process);

        if ($err) {
            echo "STDERR: $err\n";
        }

        return $out;
    }
    return null;
}

$email = "testflow_" . time() . "@example.com";
$pass = "password123";

// 1. REGISTER
echo "--- REGISTER ---\n";
$res = runAuth(['action' => 'register', 'email' => $email, 'password' => $pass]);
echo "Response: $res\n";
$json = json_decode($res, true);
if (!$json || !$json['success']) die("Register failed\n");

// Get OTP from file
$users = getU();
$otp = null;
foreach ($users as $u) if ($u['email'] == $email) $otp = $u['otp'];
echo "Fetched OTP: $otp\n";

// 2. VERIFY
echo "--- VERIFY ---\n";
$res = runAuth(['action' => 'verify', 'email' => $email, 'otp' => $otp]);
echo "Response: $res\n";
$json = json_decode($res, true);
if (!$json || !$json['success']) die("Verify failed\n");
$token = $json['token'] ?? null;
if (!$token) die("No token returned on verify!\n");
echo "Got Token: $token\n";

// 3. CHECK SESSION
echo "--- CHECK SESSION ---\n";
$res = runAuth(['action' => 'check_session', 'token' => $token]);
echo "Response: $res\n";
if (!strpos($res, '"success":true')) die("Session check failed\n");

// 4. LOGOUT
echo "--- LOGOUT ---\n";
$res = runAuth(['action' => 'logout', 'token' => $token]);
echo "Response: $res\n";

// 5. CHECK SESSION AGAIN (Should fail)
echo "--- CHECK SESSION (Expect Fail) ---\n";
$res = runAuth(['action' => 'check_session', 'token' => $token]);
echo "Response: $res\n";
if (strpos($res, '"success":true')) die("Session still valid after logout!\n");

echo "\nALL TESTS PASSED.\n";
