<?php

use App\Models\Mailbox;
use App\Models\Operator;
use App\Models\PlanFamily;
use App\Services\Dns\FakeHetznerDnsClient;
use App\Services\Dns\FakeHostDnsDirectory;
use App\Services\Dns\HetznerDnsClient;
use App\Services\Dns\HostDnsDirectory;
use App\Services\Mail\MailPurpose;
use App\Services\Monitoring\FakeMonitoringClient;
use App\Services\Monitoring\MonitoringClient;
use App\Services\Proxmox\FakeProxmoxClient;
use App\Services\Proxmox\ProxmoxClient;
use App\Services\Secrets\SecretVault;
use App\Services\Ssh\CommandResult;
use App\Services\Ssh\FakeRemoteShell;
use App\Services\Ssh\RemoteShell;
use App\Services\Traefik\FakeTraefikWriter;
use App\Services\Traefik\TraefikWriter;
use App\Services\Wireguard\FakeWireguardHub;
use App\Services\Wireguard\WireguardHub;
use App\Support\Settings;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/*
|--------------------------------------------------------------------------
| Test Case
|--------------------------------------------------------------------------
|
| The closure you provide to your test functions is always bound to a specific PHPUnit test
| case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
| need to change it using the "pest()" function to bind different classes or traits.
|
*/

pest()->extend(TestCase::class)
    ->use(RefreshDatabase::class)
    ->in('Feature');

/*
|--------------------------------------------------------------------------
| Expectations
|--------------------------------------------------------------------------
|
| When you're writing tests, you often need to check that values meet certain conditions. The
| "expect()" function gives you access to a set of "expectations" methods that you can use
| to assert different things. Of course, you may extend the Expectation API at any time.
|
*/

expect()->extend('toBeOne', function () {
    return $this->toBe(1);
});

/*
|--------------------------------------------------------------------------
| Functions
|--------------------------------------------------------------------------
|
| While Pest is very powerful out-of-the-box, you may have some testing code specific to your
| project that you don't want to repeat in every file. Here you can also expose helpers as
| global functions to help you to reduce the number of lines of code in your test files.
|
*/

function something()
{
    // ..
}

/**
 * Bind fake provisioning services into the container and return them so a test
 * can script/inspect SSH, WireGuard, Proxmox, DNS and Traefik interactions.
 *
 * @return array{shell: FakeRemoteShell, hub: FakeWireguardHub, pve: FakeProxmoxClient, dns: FakeHetznerDnsClient, hostDns: FakeHostDnsDirectory, traefik: FakeTraefikWriter}
 */
function fakeServices(): array
{
    $shell = new FakeRemoteShell;
    $hub = new FakeWireguardHub;
    $pve = new FakeProxmoxClient;
    $dns = new FakeHetznerDnsClient;
    $hostDns = new FakeHostDnsDirectory;
    $traefik = new FakeTraefikWriter;
    $monitoring = new FakeMonitoringClient;

    app()->instance(RemoteShell::class, $shell);
    app()->instance(WireguardHub::class, $hub);
    app()->instance(ProxmoxClient::class, $pve);
    app()->instance(HetznerDnsClient::class, $dns);
    app()->instance(HostDnsDirectory::class, $hostDns);
    app()->instance(TraefikWriter::class, $traefik);
    app()->instance(MonitoringClient::class, $monitoring);

    return ['shell' => $shell, 'hub' => $hub, 'pve' => $pve, 'dns' => $dns, 'hostDns' => $hostDns, 'traefik' => $traefik, 'monitoring' => $monitoring];
}

/*
| Shared account helpers. Defined here — NOT in an individual test file — so a
| targeted run (pest tests/Feature/Admin/OneFile.php) still resolves them.
|
| Both return an Operator, on the operator guard — never a User. Callers pass
| the result to actingAs()/Livewire::actingAs() with an explicit 'operator'
| guard; these helpers cannot set that for you because they only build the
| account, they do not sign anyone in.
|
| The password is fixed at 'password' (OperatorFactory's own default is
| different) because several tests exercise the real sign-in/password-change
| flow against literally that string.
*/
function operator(string $role): Operator
{
    return Operator::factory()->role($role)->create(['password' => 'password']);
}

function admin(): Operator
{
    return Operator::factory()->role('Owner')->create(['password' => 'password']);
}

/**
 * Deposits a Stripe key for whichever operating mode is current, so
 * Billing::purchase() — refusing outright without one since Task 5 — actually
 * reaches the code a test is about instead of stopping before anything is
 * touched.
 *
 * Deliberately NOT a global beforeEach(): CheckoutWithoutStripeKeyTest and
 * StripeStrictModeTest are precisely about the absence of this key, and a
 * suite-wide fixture would quietly defeat them. Call this only from a test's
 * own fixture/beforeEach where a purchase is expected to go through.
 */
function withStripeSecret(): void
{
    app(SecretVault::class)->put('stripe.secret', 'sk_test_fixture', Operator::factory()->create());
}

/**
 * Undo the mailbox-seeding migration's baseline, for tests written before it.
 *
 * RefreshDatabase migrates once per run, not once per test, so every test
 * starts from a transaction rolled back to that migrated state — including the
 * five mailboxes (no-reply, support, billing, office, info) and all five
 * mail.purpose.* settings the mailbox-seeding migration writes. The tests in
 * tests/Feature/Mail predate that migration: several create their own mailbox
 * under one of those same five keys, which now collides with mailboxes.key's
 * unique constraint; a couple rely on a purpose being genuinely unset to prove
 * MailboxResolver's system fallback, which the seeded mapping would otherwise
 * pre-empt. Call this from such a file's beforeEach() to restore the blank
 * slate it was written against.
 */
function clearMailboxSeed(): void
{
    Mailbox::query()->delete();

    foreach (MailPurpose::ALL as $purpose) {
        Settings::set(MailPurpose::settingKey($purpose), null);
    }
}

/**
 * env()'s own seam. Illuminate\Support\Env reads real process environment
 * variables (putenv()/getenv(), $_ENV, $_SERVER — Env::getRepository() chains
 * readers over all three), not config(), so config()->set() — the way every
 * other test in this suite drives behaviour — cannot touch it. This captures
 * the CURRENT value of each key exactly as env() would see it, distinguishing
 * "not set at all" (null) from "set to an empty string", so a caller can put
 * it back afterward without leaving a variable behind — or removing one — that
 * was never this test's to touch.
 *
 * @param  array<int, string>  $keys
 * @return array<string, string|null>
 */
function captureRealEnv(array $keys): array
{
    $captured = [];

    foreach ($keys as $key) {
        $value = getenv($key);
        $captured[$key] = $value === false ? null : $value;
    }

    return $captured;
}

/**
 * Writes real process environment variables through every adapter
 * Env::getRepository() might be reading from, so it does not matter which one
 * answers first. null unsets the variable entirely — distinct from '', which
 * env() would return as a real, present, empty value.
 *
 * @param  array<string, string|null>  $vars
 */
function setRealEnv(array $vars): void
{
    foreach ($vars as $key => $value) {
        if ($value === null) {
            putenv($key);
            unset($_ENV[$key], $_SERVER[$key]);
        } else {
            putenv("{$key}={$value}");
            $_ENV[$key] = $value;
            $_SERVER[$key] = $value;
        }
    }
}

/**
 * Runs $callback with the given real environment variables set, then restores
 * exactly what was there before — including "was not set at all". Use this to
 * prove behaviour that reads raw env() rather than config(); see
 * captureRealEnv()'s own docblock for why config()->set() cannot do this.
 */
function withRealEnv(array $vars, Closure $callback): mixed
{
    $previous = captureRealEnv(array_keys($vars));

    setRealEnv($vars);

    try {
        return $callback();
    } finally {
        setRealEnv($previous);
    }
}

/**
 * Was der Host auf die Zustandsfrage von EnsureNetworkBridge antwortet.
 *
 * `up` ist absichtlich EIN Wert aus drei Fakten — Brücke da, trägt die
 * Standardroute, hat eine Adresse. Der Schritt fragt sie in einem Rundlauf ab,
 * weil eine vmbr0 ohne Adresse und ohne Route eine Brücke im Sinne von
 * `ip link show` ist und sonst nichts.
 */
function scriptBridgeState(FakeRemoteShell $shell, bool $up, string $iface = 'enp0s31f6', bool $physical = true): void
{
    $shell->script('clupilot-bridge-state', CommandResult::success(implode("\n", [
        'up='.($up ? 'yes' : 'no'),
        'iface='.$iface,
        'physical='.($physical ? 'yes' : 'no'),
        'route=default via 49.12.121.65 dev '.($up ? 'vmbr0' : $iface),
        '',
    ])));
}

/**
 * Was der Host über einen laufenden Brückenbau meldet.
 *
 * `alive` wird auf dem Host gerechnet (`kill -0`), weil die PID hier nichts
 * bedeutet; `rolledback` ist die Marke, die der Zeitgeber ZULETZT setzt.
 */
function scriptBridgeStatus(FakeRemoteShell $shell, string $state, bool $alive = false, string $phase = '', string $note = '', bool $rolledBack = false): void
{
    $shell->script('clupilot-bridge-status', CommandResult::success(implode("\n", [
        'state='.$state,
        'alive='.($alive ? 'yes' : 'no'),
        'phase='.$phase,
        'note='.$note,
        'rolledback='.($rolledBack ? 'yes' : 'no'),
        '',
    ])));
}

/**
 * Was ein stehender Tunnel auf dem Host meldet.
 *
 * `date +%s` zuerst, dann eine Zeile je Peer. Beide Zeitstempel sind JETZT,
 * damit der Test nicht an einer festen Zahl hängt, die eines Tages zu alt ist —
 * die Prüfung verlangt einen FRISCHEN Handshake, nicht irgendeinen.
 *
 * Nach fakeServices() aufrufen: der Hub-Schlüssel kommt aus der gebundenen
 * Attrappe, denn genau gegen den vergleicht der Schritt.
 */
function scriptLiveTunnel(FakeRemoteShell $shell): void
{
    $now = time();
    $hub = trim(app(WireguardHub::class)->publicKey());

    $shell->script(
        'wg show wg0 latest-handshakes',
        CommandResult::success($now."\n".$hub."\t".$now),
    );
}

/**
 * Open a contract on a plan that has left the shop.
 *
 * The new ladder takes Enterprise off sale, but the contracts opened while it
 * WAS on sale keep running — a frozen snapshot each, untouched by the switch —
 * and several tests are about precisely those customers. Building one has to go
 * through OpenSubscription, which rightly refuses a plan that is not sellable,
 * so the plan is put back on sale for the length of the purchase and taken off
 * again straight after.
 *
 * That is not a way around the guard: it is the order in which a grandfathered
 * contract actually came about. The plan was on sale, somebody bought it, and
 * then it stopped being sold.
 *
 * @template T
 *
 * @param  callable(): T  $buy
 * @return T
 */
function asGrandfathered(string $planKey, callable $buy): mixed
{
    $family = PlanFamily::query()->where('key', $planKey)->sole();
    $wasOnSale = $family->sales_enabled;

    PlanFamily::query()->whereKey($family->getKey())->update(['sales_enabled' => true]);

    try {
        return $buy();
    } finally {
        PlanFamily::query()->whereKey($family->getKey())->update(['sales_enabled' => $wasOnSale]);
    }
}
