<?php

namespace Tests\Unit;

use App\Models\Package;
use App\Models\Tenant;
use App\Services\Paddle\PaddleCheckoutService;
use App\Services\Paddle\PaddleClient;
use App\Services\Paddle\PaddleCustomerService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery;
use Tests\TestCase;

class PaddleCheckoutServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_create_checkout_sends_custom_data_payload(): void
    {
        $tenant = Tenant::factory()->create([
            'contact_email' => 'buyer@example.com',
        ]);

        $package = Package::factory()->create([
            'paddle_price_id' => 'pri_123',
        ]);

        $client = Mockery::mock(PaddleClient::class);
        $customers = Mockery::mock(PaddleCustomerService::class);

        $customers->shouldReceive('ensureCustomerId')
            ->once()
            ->with($tenant)
            ->andReturn('ctm_123');

        $client->shouldReceive('post')
            ->once()
            ->with('/transactions', Mockery::on(function (array $payload) use ($tenant, $package) {
                return $payload['items'][0]['price_id'] === 'pri_123'
                    && $payload['customer_id'] === 'ctm_123'
                    && ($payload['custom_data']['tenant_id'] ?? null) === (string) $tenant->id
                    && ($payload['custom_data']['package_id'] ?? null) === (string) $package->id
                    && ($payload['custom_data']['source'] ?? null) === 'test'
                    && ($payload['custom_data']['success_url'] ?? null) === 'https://example.test/success'
                    && ($payload['custom_data']['cancel_url'] ?? null) === 'https://example.test/cancel'
                    && ! isset($payload['metadata'])
                    && ! isset($payload['success_url'])
                    && ! isset($payload['cancel_url'])
                    && ! isset($payload['customer_email']);
            }))
            ->andReturn(['data' => ['checkout' => ['url' => 'https://paddle.test/checkout/123'], 'id' => 'txn_123']]);

        $this->app->instance(PaddleClient::class, $client);
        $this->app->instance(PaddleCustomerService::class, $customers);

        $service = $this->app->make(PaddleCheckoutService::class);

        $checkout = $service->createCheckout($tenant, $package, [
            'success_url' => 'https://example.test/success',
            'return_url' => 'https://example.test/cancel',
            'metadata' => ['source' => 'test'],
        ]);

        $this->assertSame('https://paddle.test/checkout/123', $checkout['checkout_url']);
        $this->assertSame('txn_123', $checkout['id']);
    }
}
