<?php

declare(strict_types=1);

use App\Models\Invoice;
use App\Models\User;
use Database\Seeders\RoleAndPermissionSeeder;

beforeEach(function (): void {
    $this->seed(RoleAndPermissionSeeder::class);
    $this->accountUrl = 'http://'.config('app.domains.account');
});

it('displays the billing index page', function (): void {
    $user = User::factory()->create();

    $this->actingAs($user)
        ->get($this->accountUrl.'/billing')
        ->assertOk()
        ->assertInertia(fn ($page) => $page
            ->component('Billing/Index')
            ->has('paymentMethods')
            ->has('invoices')
            ->has('transactions')
        );
});

it('displays the invoices page', function (): void {
    $user = User::factory()->create();
    Invoice::factory()->count(3)->create(['user_id' => $user->id]);

    $this->actingAs($user)
        ->get($this->accountUrl.'/billing/invoices')
        ->assertOk()
        ->assertInertia(fn ($page) => $page
            ->component('Billing/Invoices')
            ->has('invoices.data', 3)
        );
});

it('displays the transactions page', function (): void {
    $user = User::factory()->create();

    $this->actingAs($user)
        ->get($this->accountUrl.'/billing/transactions')
        ->assertOk()
        ->assertInertia(fn ($page) => $page
            ->component('Billing/Transactions')
            ->has('transactions')
        );
});

it('prevents downloading another users invoice', function (): void {
    $user = User::factory()->create();
    $otherUser = User::factory()->create();
    $invoice = Invoice::factory()->create(['user_id' => $otherUser->id]);

    $this->actingAs($user)
        ->get($this->accountUrl.'/billing/invoices/'.$invoice->id.'/download')
        ->assertForbidden();
});

it('allows downloading own invoice', function (): void {
    $user = User::factory()->create();
    $invoice = Invoice::factory()->create(['user_id' => $user->id]);

    $this->actingAs($user)
        ->get($this->accountUrl.'/billing/invoices/'.$invoice->id.'/download')
        ->assertOk();
});

it('requires authentication to view billing', function (): void {
    $this->get($this->accountUrl.'/billing')
        ->assertRedirect();
});
