<?php

declare(strict_types=1);

use io\billdesk\client\hmacsha256\BillDeskJWEHS256Client;
use io\billdesk\client\hmacsha256\Config;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use PHPUnit\Framework\TestCase;

class CreateOrderTest extends TestCase
{
    private BillDeskJWEHS256Client $client;
    private Logger $logger;

    protected function setUp(): void
    {
        // Set up configuration
        $config = new Config();
        $config->setClientId("SYMM1230");
        $config->setMerchantId("BDMONITOR");
        $config->setEncryptionKeyBase64("U1lNTUpPU0VFTkNSREVDUlNZTU1KT1NFRU5DUkRFQ1I=");
        $config->setSigningKeyBase64("U1lNTUpPU0VFTkNSREVDUioqKioqKioqKioqKioqKio=");
        $config->setEncryptionKeyId("HMAC");
        $config->setSigningKeyId("AES_DIR");

        // Set up logger
        $this->logger = new Logger("billdesk-test");
        $this->logger->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG));

        $this->logger->info("Encryption Key Length", ['length' => strlen(base64_decode($config->getEncryptionKeyBase64()))]);
        $this->logger->info("Signing Key Length", ['length' => strlen(base64_decode($config->getSigningKeyBase64()))]);

        // Instantiate client
        $this->client = new BillDeskJWEHS256Client($config, "https://uat1.billdesk.com/u2");
        $this->client->setLogger($this->logger);
    }

    public function testCreateOrder(): void
    {
        $orderId = uniqid();
        $orderDate = (new \DateTime('now', new \DateTimeZone('Asia/Kolkata')))->format(DATE_W3C);

        $request = [
            'mercid'     => "BDMONITOR",
            'orderid'    => $orderId,
            'amount'     => "1.0",
            'order_date' => $orderDate,
            'currency'   => "356",
            'ru'         => "https://www.billdesk.io",
            'itemcode'   => "DIRECT",
            'device'     => [
                'init_channel' => 'internet',
                'ip'           => "192.168.1.1",
                'user_agent'   => 'Mozilla/5.0',
            ],
        ];

        $this->logger->info("Creating order", ['request' => $request]);

        try {
            $response = $this->client->createOrder($request);
            $responseData = $response->getResponse();

            $this->assertEquals('ACTIVE', $responseData['status'] ?? null);
            $this->assertNotEmpty($responseData['bdorderid'] ?? null);

            $this->logger->info("Decrypted full response status", ['responseStatus' => $responseData['status']]);
            //fwrite(STDOUT, print_r($responseData, true));
        } catch (\Exception $e) {
            $this->logger->error("Request failed", ['exception' => $e]);
            throw $e;
        }
    }
}
