<?php

namespace Tests\Feature\Tenant;

use App\Models\Event;
use App\Models\EventPackage;
use App\Models\EventPackageAddon;
use App\Models\Package;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;

class EventAddonCheckoutTest extends TenantTestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        Config::set('package-addons.extra_photos_small', [
            'label' => 'Extra photos (500)',
            'price_id' => 'pri_addon_photos',
            'increments' => ['extra_photos' => 500],
        ]);

        Config::set('paddle.api_key', 'test_key');
        Config::set('paddle.base_url', 'https://paddle.test');
        Config::set('paddle.environment', 'sandbox');

        // Fake Paddle response
        Http::fake([
            '*/customers' => Http::response([
                'data' => [
                    'id' => 'ctm_addon_123',
                ],
            ], 200),
            '*/transactions' => Http::response([
                'data' => [
                    'id' => 'txn_addon_123',
                    'checkout' => [
                        'url' => 'https://checkout.paddle.test/abcd',
                    ],
                ],
            ], 200),
        ]);
    }

    public function test_checkout_creates_pending_addon_record(): void
    {
        $package = Package::factory()->endcustomer()->create([
            'max_photos' => 100,
            'max_guests' => 50,
            'gallery_days' => 7,
        ]);

        $event = Event::factory()->for($this->tenant)->create([
            'status' => 'published',
        ]);

        $eventPackage = EventPackage::create([
            'event_id' => $event->id,
            'package_id' => $package->id,
            'purchased_price' => $package->price,
            'purchased_at' => now(),
            'used_photos' => 0,
            'used_guests' => 0,
            'gallery_expires_at' => now()->addDays(7),
        ]);

        $response = $this->authenticatedRequest('POST', "/api/v1/tenant/events/{$event->slug}/addons/checkout", [
            'addon_key' => 'extra_photos_small',
            'quantity' => 2,
            'accepted_terms' => true,
            'accepted_waiver' => true,
        ]);

        $response->assertOk();
        $response->assertJsonPath('checkout_id', 'txn_addon_123');

        $this->assertDatabaseHas('event_package_addons', [
            'event_package_id' => $eventPackage->id,
            'addon_key' => 'extra_photos_small',
            'status' => 'pending',
            'quantity' => 2,
            'transaction_id' => 'txn_addon_123',
        ]);

        $addon = EventPackageAddon::where('event_package_id', $eventPackage->id)->latest()->first();
        $this->assertSame(1000, $addon->extra_photos); // increments * quantity
    }
}
