<?php

namespace Tests\Unit;

use App\Enums\CouponType;
use App\Models\Coupon;
use App\Services\Paddle\PaddleClient;
use App\Services\Paddle\PaddleDiscountService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery;
use Tests\TestCase;

class PaddleDiscountServiceTest extends TestCase
{
    use RefreshDatabase;

    protected function tearDown(): void
    {
        parent::tearDown();

        Mockery::close();
    }

    public function test_build_payload_uses_description_fallback_and_excludes_name_and_starts_at(): void
    {
        $coupon = Coupon::factory()->create([
            'name' => 'Launch Discount',
            'description' => null,
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addWeek(),
            'type' => CouponType::PERCENTAGE,
            'amount' => 10,
        ]);

        $service = new TestablePaddleDiscountService(Mockery::mock(PaddleClient::class));

        $payload = $service->buildPayload($coupon);

        $this->assertSame('Launch Discount', $payload['description']);
        $this->assertArrayNotHasKey('name', $payload);
        $this->assertArrayNotHasKey('starts_at', $payload);
    }

    public function test_build_payload_formats_flat_discount_amount_and_currency(): void
    {
        $coupon = Coupon::factory()->create([
            'type' => CouponType::FLAT,
            'amount' => 25.50,
            'currency' => 'eur',
            'description' => 'Flat discount',
        ]);

        $service = new TestablePaddleDiscountService(Mockery::mock(PaddleClient::class));

        $payload = $service->buildPayload($coupon);

        $this->assertSame('2550', $payload['amount']);
        $this->assertSame('EUR', $payload['currency_code']);
    }

    public function test_build_payload_removes_currency_for_percentage_discounts(): void
    {
        $coupon = Coupon::factory()->create([
            'type' => CouponType::PERCENTAGE,
            'amount' => 15,
            'currency' => 'EUR',
            'description' => 'Percent discount',
        ]);

        $service = new TestablePaddleDiscountService(Mockery::mock(PaddleClient::class));

        $payload = $service->buildPayload($coupon);

        $this->assertSame('15.00', $payload['amount']);
        $this->assertArrayNotHasKey('currency_code', $payload);
    }
}

class TestablePaddleDiscountService extends PaddleDiscountService
{
    /**
     * @return array<string, mixed>
     */
    public function buildPayload(Coupon $coupon): array
    {
        return $this->buildDiscountPayload($coupon);
    }
}
