<?php

namespace Tests\Feature\Checkout;

use App\Models\CheckoutSession;
use App\Models\Package;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;

class CheckoutFreeActivationTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        Mail::fake();
        Notification::fake();
    }

    public function test_free_checkout_activation_completes_session_and_assigns_package(): void
    {
        $tenant = Tenant::factory()->create();
        $user = User::factory()->for($tenant)->create();
        $package = Package::factory()->create([
            'price' => 0,
        ]);

        $this->actingAs($user);

        $response = $this->postJson(route('checkout.free-activate'), [
            'package_id' => $package->id,
            'accepted_terms' => true,
            'locale' => 'de',
        ]);

        $response->assertOk()
            ->assertJsonPath('status', 'completed');

        $this->assertDatabaseHas('checkout_sessions', [
            'package_id' => $package->id,
            'user_id' => $user->id,
            'provider' => CheckoutSession::PROVIDER_FREE,
            'status' => CheckoutSession::STATUS_COMPLETED,
        ]);

        $this->assertDatabaseHas('tenant_packages', [
            'tenant_id' => $tenant->id,
            'package_id' => $package->id,
            'active' => true,
        ]);

        $this->assertDatabaseHas('package_purchases', [
            'tenant_id' => $tenant->id,
            'package_id' => $package->id,
            'provider' => CheckoutSession::PROVIDER_FREE,
        ]);
    }

    public function test_free_checkout_does_not_require_waiver_before_first_use(): void
    {
        $tenant = Tenant::factory()->create();
        $user = User::factory()->for($tenant)->create();
        $package = Package::factory()->create([
            'price' => 0,
        ]);

        $this->actingAs($user);

        $response = $this->postJson(route('checkout.free-activate'), [
            'package_id' => $package->id,
            'accepted_terms' => true,
            'locale' => 'de',
        ]);

        $response->assertOk()
            ->assertJsonPath('status', 'completed');

        $this->assertDatabaseHas('package_purchases', [
            'tenant_id' => $tenant->id,
            'package_id' => $package->id,
        ]);
    }
}
