<?php

use App\Livewire\Admin\Revenue;
use App\Models\Customer;
use App\Models\Subscription;
use Livewire\Livewire;

/**
 * A granted contract at 0 must not drag ARPU down or count as revenue-bearing
 * — and the owner measures himself on the number of granted contracts too, so
 * it is shown separately rather than folded into MRR/ARR/ARPU/contracts.
 */
it('excludes a granted contract from MRR, ARR and the contracts count', function () {
    $customer = Customer::factory()->create();

    Subscription::factory()->create([
        'customer_id' => $customer->id,
        'status' => 'active', 'term' => 'monthly', 'price_cents' => 17900, 'currency' => 'EUR',
    ]);

    Subscription::factory()->create([
        'customer_id' => $customer->id,
        'status' => 'active', 'term' => 'monthly', 'price_cents' => 0, 'currency' => 'EUR',
        'granted_at' => now(), 'catalogue_price_cents' => 17900,
    ]);

    $component = Livewire::actingAs(operator('Owner'), 'operator')->test(Revenue::class);

    // Only the paying contract's 179,00 shows in MRR — a granted contract
    // adding its 0 would still inflate the contracts count underneath ARPU.
    $component->assertViewHas('kpis', function (array $kpis) {
        [$mrr, , $arpu, $contracts, $granted] = $kpis;

        return str_contains($mrr['value'], '179,00')
            && str_contains($arpu['value'], '179,00')
            && $contracts['value'] === '1'
            && $granted['value'] === '1';
    });
});

it('folds a discount into revenue at what the customer actually pays, but still counts it as granted', function () {
    $customer = Customer::factory()->create();

    Subscription::factory()->create([
        'customer_id' => $customer->id,
        'status' => 'active', 'term' => 'monthly', 'price_cents' => 5000, 'currency' => 'EUR',
        'granted_at' => now(), 'catalogue_price_cents' => 17900,
    ]);

    $component = Livewire::actingAs(operator('Owner'), 'operator')->test(Revenue::class);

    // A discount is still an operator's grant, so — like a full gift — it is
    // excluded from what the owner counts as a sale.
    $component->assertViewHas('kpis', function (array $kpis) {
        [$mrr, , , $contracts, $granted] = $kpis;

        return str_contains($mrr['value'], '0,00')
            && $contracts['value'] === '0'
            && $granted['value'] === '1';
    });
});
