<?php

declare(strict_types=1);

require __DIR__ . '/dev-db.php';
require __DIR__ . '/../app/saas-auth.php';

function auth_check_assert(string $label, bool $condition, array &$failures, int &$passes): void
{
    if ($condition) {
        $passes++;
        echo "PASS {$label}\n";
        return;
    }

    $failures[] = $label;
    echo "FAIL {$label}\n";
}

function auth_check_cleanup(PDO $pdo, string $slug, string $emailNorm): void
{
    $stmt = $pdo->prepare('SELECT id FROM tenants WHERE slug = ?');
    $stmt->execute([$slug]);
    $tenantId = $stmt->fetchColumn();

    if ($tenantId !== false) {
        $tenantId = (int)$tenantId;
        $pdo->prepare('DELETE FROM participants WHERE tenant_id = ?')->execute([$tenantId]);
        $pdo->prepare('DELETE FROM tenant_memberships WHERE tenant_id = ?')->execute([$tenantId]);
        $pdo->prepare('DELETE FROM tenant_settings WHERE tenant_id = ?')->execute([$tenantId]);
        $pdo->prepare('DELETE FROM tenants WHERE id = ?')->execute([$tenantId]);
    }

    $pdo->prepare('DELETE FROM users WHERE email_norm = ?')->execute([$emailNorm]);
}

$pdo = dev_pdo();
dev_apply_schema($pdo);

$slug = 'm3-auth-flow-check';
$email = 'm3-auth-flow-check@test.local';
$emailNorm = saas_email_norm($email);
$password = 'M3-auth-flow-123';
$failures = [];
$passes = 0;

auth_check_cleanup($pdo, $slug, $emailNorm);

$result = saas_register_tenant_owner($pdo, [
    'tenant_name' => 'M3 Auth Flow Check',
    'tenant_slug' => $slug,
    'display_name' => 'M3 Auth Check',
    'email' => $email,
    'password' => $password,
    'password_confirm' => $password,
]);

auth_check_assert('registration succeeds', $result['ok'] === true, $failures, $passes);

if ($result['ok']) {
    $tenantId = (int)$result['identity']['tenant_id'];
    $userId = (int)$result['identity']['user_id'];

    $stmt = $pdo->prepare('SELECT COUNT(*) FROM tenants WHERE id = ? AND slug = ?');
    $stmt->execute([$tenantId, $slug]);
    auth_check_assert('tenant is persisted', (int)$stmt->fetchColumn() === 1, $failures, $passes);

    $stmt = $pdo->prepare('SELECT COUNT(*) FROM tenant_settings WHERE tenant_id = ?');
    $stmt->execute([$tenantId]);
    auth_check_assert('tenant settings are persisted', (int)$stmt->fetchColumn() === 1, $failures, $passes);

    $stmt = $pdo->prepare('SELECT COUNT(*) FROM tenant_memberships WHERE tenant_id = ? AND user_id = ? AND role = ?');
    $stmt->execute([$tenantId, $userId, 'owner']);
    auth_check_assert('owner membership is persisted', (int)$stmt->fetchColumn() === 1, $failures, $passes);

    $stmt = $pdo->prepare('SELECT COUNT(*) FROM participants WHERE tenant_id = ? AND user_id = ? AND email_norm = ?');
    $stmt->execute([$tenantId, $userId, $emailNorm]);
    auth_check_assert('owner participant is persisted', (int)$stmt->fetchColumn() === 1, $failures, $passes);
}

$login = saas_authenticate($pdo, $email, $password, $slug);
auth_check_assert('login succeeds', $login['ok'] === true, $failures, $passes);
if ($login['ok']) {
    auth_check_assert('login returns owner role', $login['identity']['role'] === 'owner', $failures, $passes);
    auth_check_assert('login returns tenant slug', $login['identity']['tenant_slug'] === $slug, $failures, $passes);
}

$badLogin = saas_authenticate($pdo, $email, 'wrong-password', $slug);
auth_check_assert('wrong password is rejected', $badLogin['ok'] === false, $failures, $passes);

auth_check_cleanup($pdo, $slug, $emailNorm);

if ($failures !== []) {
    echo "\nM3 auth flow check failed with " . count($failures) . " failure(s):\n";
    foreach ($failures as $failure) {
        echo "- {$failure}\n";
    }
    exit(1);
}

echo "\nM3 auth flow check passed with {$passes} assertions.\n";
