<?php

namespace Tests\Unit;

use App\Services\PayPlus;
use Tests\TestCase;

class PayPlusServiceTest extends TestCase
{
    /** @test */
    public function it_builds_payout_sign_with_flattened_sorted_payload()
    {
        $service = new PayPlus([
            'appKey' => '123456',
        ]);

        $payload = [
            'k2' => [1, 2],
            'empty' => '',
            'k3' => [
                'b1' => 'test1',
                'a2' => 'test2',
            ],
            'k1' => 1,
            'null_value' => null,
        ];

        $sign = $service->signPayoutPayload($payload);

        $this->assertSame(
            hash('sha256', 'k1=1&k2=[1,2]&k3_a2=test2&k3_b1=test1' . '123456'),
            $sign
        );
    }

    /** @test */
    public function it_encrypts_and_decrypts_component_delta_with_aes_gcm()
    {
        $service = new PayPlus([]);
        $aesKey = str_repeat('01', 32);
        $iv = str_repeat('02', 12);
        $payload = '{"hello":"payplus"}';

        $encrypted = $service->encryptComponentDelta($payload, $aesKey, $iv);
        $decrypted = $service->decryptComponentDelta($encrypted, $aesKey, $iv);

        $this->assertSame($payload, $decrypted);
    }

    /** @test */
    public function it_builds_beneficiary_payload_with_safe_defaults()
    {
        $service = new PayPlus([]);

        $payload = $service->buildBeneficiaryPayload([
            'user_id' => 10001,
            'email' => '',
            'phone' => '',
            'first_name' => '',
            'last_name' => '',
        ], 1234567890);

        $this->assertSame('10001', $payload['payee_id']);
        $this->assertSame('en', $payload['language']);
        $this->assertSame('US', $payload['country']);
        $this->assertSame('+1-0000000000', $payload['phone']);
        $this->assertSame('unknown10001@example.com', $payload['email']);
        $this->assertSame('unknown', $payload['first_name']);
        $this->assertSame('user', $payload['last_name']);
        $this->assertSame(1234567890, $payload['timestamp']);
    }
}
