<?php

namespace Tests\Feature\Specimen;

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

class ContainerPatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    protected string $token;
    protected string $endpoint = 'api/specimen/container';

    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 createContainer(array $data = []): array
    {
        $payload = array_merge([
            'ConCode' => 'CON_' . uniqid(),
            'ConName' => 'Test Container ' . uniqid(),
        ], $data);

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

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

    public function testPartialUpdateContainerSuccess()
    {
        $container = $this->createContainer();
        $id = $container['ConDefID'];

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

        $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 Container', $showData['ConName']);
        $this->assertEquals($container['ConCode'], $showData['ConCode']);
    }

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

        $patch->assertStatus(404);
    }

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateContainerEmptyPayload()
    {
        $container = $this->createContainer();
        $id = $container['ConDefID'];

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateContainerSingleField()
    {
        $container = $this->createContainer();
        $id = $container['ConDefID'];

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

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

        $this->assertNotEquals($container['ConCode'], $showData['ConCode']);
        $this->assertEquals($container['ConName'], $showData['ConName']);
    }
}
