<?php

use App\Livewire\Billing;
use App\Models\Customer;
use App\Models\Instance;
use App\Models\Order;
use App\Models\Subscription;
use App\Models\User;
use App\Services\Stripe\FakeStripeClient;
use App\Services\Stripe\StripeClient;
use Livewire\Livewire;

/**
 * Bis hierher stand im Portal NICHTS, wenn eine Abbuchung scheiterte.
 * `ApplyStripeBillingEvent::invoicePaymentFailed()` setzt `past_due` und
 * schweigt — der Kunde erfuhr davon erst, wenn seine Cloud stand.
 */
function portalCustomerWith(string $stripeStatus): User
{
    $user = User::factory()->create(['email' => 'faellig@portal.test', 'is_admin' => false]);
    $customer = Customer::factory()->create(['email' => 'faellig@portal.test', 'stripe_customer_id' => 'cus_42']);
    $order = Order::factory()->create(['customer_id' => $customer->id, 'plan' => 'start']);
    Instance::factory()->create([
        'customer_id' => $customer->id, 'order_id' => $order->id,
        'plan' => 'start', 'status' => 'active',
    ]);
    Subscription::factory()->create([
        'customer_id' => $customer->id, 'stripe_status' => $stripeStatus,
    ]);

    withStripeSecret();
    app()->instance(StripeClient::class, new FakeStripeClient);

    return $user;
}

it('says plainly that a payment failed', function () {
    Livewire::actingAs(portalCustomerWith('past_due'))
        ->test(Billing::class)
        ->assertSee(__('billing.past_due_title'));
});

it('stays quiet when nothing is owed', function () {
    // Ein Hinweis, der immer da ist, ist keiner.
    Livewire::actingAs(portalCustomerWith('active'))
        ->test(Billing::class)
        ->assertDontSee(__('billing.past_due_title'));
});

it('still renders for a customer who has never been to the checkout', function () {
    // Der Fehler, den ich beim ersten Anlauf gebaut habe: die zwei Bauteile
    // waren bedingungslos eingebettet, und beide brechen ohne Stripe-Kunden
    // mit 404 ab. 53 Bestandstests fielen um — jeder Kunde ohne
    // stripe_customer_id bekam statt seiner Abrechnungsseite eine 404.
    $user = User::factory()->create(['email' => 'ohnestripe@portal.test', 'is_admin' => false]);
    Customer::factory()->create(['email' => 'ohnestripe@portal.test', 'stripe_customer_id' => null]);

    Livewire::actingAs($user)
        ->test(Billing::class)
        ->assertOk()
        ->assertDontSee(__('billing.invoices_open_title'));
});
