<?php

namespace Tests\Unit;

use App\Services\GiftVouchers\GiftVoucherCheckoutService;
use App\Services\Paddle\PaddleClient;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery;
use Tests\TestCase;

class GiftVoucherCheckoutServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_lists_tiers_with_checkout_flag(): void
    {
        config()->set('gift-vouchers.tiers', [
            ['key' => 'gift-a', 'label' => 'A', 'amount' => 10, 'currency' => 'EUR', 'paddle_price_id' => 'pri_a'],
            ['key' => 'gift-b', 'label' => 'B', 'amount' => 20, 'currency' => 'EUR', 'paddle_price_id' => null],
        ]);

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

        $tiers = $service->tiers();

        $this->assertCount(2, $tiers);
        $this->assertTrue($tiers[0]['can_checkout']);
        $this->assertFalse($tiers[1]['can_checkout']);
    }

    public function test_it_creates_checkout_link_with_metadata(): void
    {
        config()->set('gift-vouchers.tiers', [
            ['key' => 'gift-a', 'label' => 'A', 'amount' => 10, 'currency' => 'EUR', 'paddle_price_id' => 'pri_a'],
        ]);

        $client = Mockery::mock(PaddleClient::class);
        $client->shouldReceive('post')
            ->once()
            ->with('/customers', Mockery::on(function ($payload) {
                return $payload['email'] === 'buyer@example.com';
            }))
            ->andReturn(['data' => ['id' => 'ctm_123']]);
        $client->shouldReceive('post')
            ->once()
            ->with('/transactions', Mockery::on(function ($payload) {
                return $payload['items'][0]['price_id'] === 'pri_a'
                    && $payload['customer_id'] === 'ctm_123'
                    && $payload['custom_data']['type'] === 'gift_voucher';
            }))
            ->andReturn(['data' => ['checkout' => ['url' => 'https://paddle.test/checkout/123'], 'id' => 'txn_123']]);

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

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

        $checkout = $service->create([
            'tier_key' => 'gift-a',
            'purchaser_email' => 'buyer@example.com',
            'recipient_email' => 'friend@example.com',
            'recipient_name' => 'Friend',
            'message' => 'Hi',
        ]);

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