<?php

namespace Tests\Feature;

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

class CheckoutSessionLocalConfirmationTest extends TestCase
{
    use RefreshDatabase;

    public function test_local_confirmation_marks_checkout_completed(): void
    {
        $this->app['env'] = 'local';
        Mail::fake();
        Notification::fake();

        $tenant = Tenant::factory()->create();
        $user = User::factory()->for($tenant)->create();
        $package = Package::factory()->create([
            'paddle_price_id' => 'pri_123',
            'paddle_product_id' => 'pro_123',
            'price' => 120,
        ]);

        $sessions = app(CheckoutSessionService::class);
        $session = $sessions->createOrResume($user, $package, [
            'tenant' => $tenant,
        ]);
        $sessions->selectProvider($session, 'paddle');

        $this->actingAs($user);
        $this->withSession(['_token' => 'test-token']);

        $response = $this->postJson(
            route('checkout.session.confirm', $session),
            [
                'transaction_id' => 'txn_123',
                'checkout_id' => 'chk_123',
            ],
            [
                'X-CSRF-TOKEN' => 'test-token',
            ]
        );

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

        $this->assertDatabaseHas('checkout_sessions', [
            'id' => $session->id,
            'status' => 'completed',
        ]);

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

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