<?php

namespace Tests\Feature\Tenant;

use App\Models\Package;
use App\Services\Paddle\PaddleCheckoutService;
use Mockery;

class TenantPaddleCheckoutTest extends TenantTestCase
{
    protected function tearDown(): void
    {
        Mockery::close();

        parent::tearDown();
    }

    public function test_tenant_can_create_paddle_checkout(): void
    {
        $package = Package::factory()->create([
            'paddle_price_id' => 'pri_test_123',
            'price' => 129,
        ]);

        $checkoutService = Mockery::mock(PaddleCheckoutService::class);
        $checkoutService->shouldReceive('createCheckout')
            ->once()
            ->withArgs(function ($tenant, $payloadPackage, array $payload) use ($package) {
                return $tenant->is($this->tenant)
                    && $payloadPackage->is($package)
                    && array_key_exists('success_url', $payload)
                    && array_key_exists('return_url', $payload)
                    && array_key_exists('metadata', $payload)
                    && is_array($payload['metadata'])
                    && ! empty($payload['metadata']['checkout_session_id']);
            })
            ->andReturn([
                'checkout_url' => 'https://checkout.paddle.test/checkout/123',
                'id' => 'chk_test_123',
            ]);
        $this->instance(PaddleCheckoutService::class, $checkoutService);

        $response = $this->authenticatedRequest('POST', '/api/v1/tenant/packages/paddle-checkout', [
            'package_id' => $package->id,
        ]);

        $response->assertOk()
            ->assertJsonPath('checkout_url', 'https://checkout.paddle.test/checkout/123')
            ->assertJsonStructure(['checkout_session_id']);
    }

    public function test_paddle_checkout_requires_paddle_price_id(): void
    {
        $package = Package::factory()->create([
            'paddle_price_id' => null,
            'price' => 129,
        ]);

        $response = $this->authenticatedRequest('POST', '/api/v1/tenant/packages/paddle-checkout', [
            'package_id' => $package->id,
        ]);

        $response->assertStatus(422)
            ->assertJsonStructure([
                'errors' => [
                    'package_id' => [],
                ],
            ]);
    }
}
