<?php

namespace Tests\Feature\OrderTest;

use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\CIUnitTestCase;
use Firebase\JWT\JWT;

class OrderTestPatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    protected string $token;
    protected string $endpoint = 'api/ordertest';

    protected function setUp(): void
    {
        parent::setUp();
        $key = getenv('JWT_SECRET') ?: 'my-secret-key';
        $payload = [
            'iss' => 'localhost',
            'aud' => 'localhost',
            'iat' => time(),
            'nbf' => time(),
            'exp' => time() + 3600,
            'uid' => 1,
            'email' => 'admin@admin.com',
        ];
        $this->token = JWT::encode($payload, $key, 'HS256');
    }

    private function authHeaders(): array
    {
        return ['Cookie' => 'token=' . $this->token];
    }

    private function createOrderTest(array $data = []): array
    {
        $payload = array_merge([
            'OrderCode' => 'ORD_' . uniqid(),
            'OrderName' => 'Test Order ' . uniqid(),
        ], $data);

        $response = $this->withHeaders($this->authHeaders())
                         ->withBodyFormat('json')
                         ->call('post', $this->endpoint, $payload);

        $response->assertStatus(201);
        $decoded = json_decode($response->getJSON(), true);
        return $decoded['data'];
    }

    public function testPartialUpdateOrderTestSuccess()
    {
        $order = $this->createOrderTest();
        $id = $order['OrderID'];

        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/{$id}", ['OrderName' => 'Updated Order']);

        $patch->assertStatus(200);
        $patchData = json_decode($patch->getJSON(), true);
        $this->assertEquals('success', $patchData['status']);

        $show = $this->withHeaders($this->authHeaders())->call('get', "{$this->endpoint}/{$id}");
        $show->assertStatus(200);
        $showData = json_decode($show->getJSON(), true)['data'];

        $this->assertEquals('Updated Order', $showData['OrderName']);
        $this->assertEquals($order['OrderCode'], $showData['OrderCode']);
    }

    public function testPartialUpdateOrderTestNotFound()
    {
        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/999999", ['OrderName' => 'Updated']);

        $patch->assertStatus(404);
    }

    public function testPartialUpdateOrderTestInvalidId()
    {
        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/invalid", ['OrderName' => 'Updated']);

        $patch->assertStatus(400);
    }

    public function testPartialUpdateOrderTestEmptyPayload()
    {
        $order = $this->createOrderTest();
        $id = $order['OrderID'];

        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/{$id}", []);

        $patch->assertStatus(400);
    }

    public function testPartialUpdateOrderTestSingleField()
    {
        $order = $this->createOrderTest();
        $id = $order['OrderID'];

        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/{$id}", ['OrderCode' => 'NEW_' . uniqid()]);

        $patch->assertStatus(200);
        $showData = json_decode($this->withHeaders($this->authHeaders())
                                     ->call('get', "{$this->endpoint}/{$id}")
                                     ->getJSON(), true)['data'];

        $this->assertNotEquals($order['OrderCode'], $showData['OrderCode']);
        $this->assertEquals($order['OrderName'], $showData['OrderName']);
    }
}
