<?php

declare(strict_types=1);

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

function settings_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 settings_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-settings-flow-check';
$email = 'm3-settings-flow-check@test.local';
$emailNorm = saas_email_norm($email);
$password = 'M3-settings-flow-123';
$failures = [];
$passes = 0;

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

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

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

if ($registration['ok']) {
    $identity = $registration['identity'];
    $tenantId = (int)$identity['tenant_id'];
    settings_check_assert('owner can manage settings', saas_can_manage_tenant_settings($identity), $failures, $passes);
    settings_check_assert(
        'member cannot manage settings',
        !saas_can_manage_tenant_settings(['role' => 'member']),
        $failures,
        $passes
    );

    $settings = saas_fetch_tenant_settings($pdo, $tenantId);
    settings_check_assert('settings can be fetched', $settings !== null, $failures, $passes);
    if ($settings !== null) {
        settings_check_assert('default mark price is 20 cents', $settings['mark_price_cents'] === 20, $failures, $passes);
    }

    $update = saas_update_tenant_settings($pdo, $tenantId, [
        'tenant_name' => 'M3 Settings Flow Updated',
        'timezone' => 'Europe/Berlin',
        'locale' => 'de-DE',
        'currency_code' => 'EUR',
        'mark_price' => '0,35',
        'sheet_window_days' => '90',
        'negative_warning' => '12,50',
        'paypal_url_template' => 'https://paypal.example/m3/',
        'self_entry_enabled' => '1',
        'paypal_enabled' => '1',
    ]);

    settings_check_assert('settings update succeeds', $update['ok'] === true, $failures, $passes);

    $updated = saas_fetch_tenant_settings($pdo, $tenantId);
    settings_check_assert('updated settings can be fetched', $updated !== null, $failures, $passes);
    if ($updated !== null) {
        settings_check_assert('tenant name is updated', $updated['name'] === 'M3 Settings Flow Updated', $failures, $passes);
        settings_check_assert('mark price is updated', $updated['mark_price_cents'] === 35, $failures, $passes);
        settings_check_assert('sheet window is updated', $updated['sheet_window_days'] === 90, $failures, $passes);
        settings_check_assert('negative warning is stored negative', $updated['negative_warning_cents'] === -1250, $failures, $passes);
        settings_check_assert('paypal is enabled', $updated['paypal_enabled'] === 1, $failures, $passes);
        settings_check_assert('self entry is enabled', $updated['self_entry_enabled'] === 1, $failures, $passes);
    }
}

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

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

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