<?php

namespace Tests\Feature\Organization;

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

class HostComParaPatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    protected string $token;
    protected string $endpoint = 'api/organization/hostcompara';

    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 createHostComPara(array $data = []): array
    {
        $payload = array_merge([
            'HostComParaCode' => 'HCP_' . uniqid(),
            'HostComParaName' => 'Test HostComPara ' . 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 testPartialUpdateHostComParaSuccess()
    {
        $para = $this->createHostComPara();
        $id = $para['HostComParaID'];

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

        $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 HostComPara', $showData['HostComParaName']);
        $this->assertEquals($para['HostComParaCode'], $showData['HostComParaCode']);
    }

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

        $patch->assertStatus(404);
    }

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateHostComParaEmptyPayload()
    {
        $para = $this->createHostComPara();
        $id = $para['HostComParaID'];

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateHostComParaSingleField()
    {
        $para = $this->createHostComPara();
        $id = $para['HostComParaID'];

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

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

        $this->assertNotEquals($para['HostComParaCode'], $showData['HostComParaCode']);
        $this->assertEquals($para['HostComParaName'], $showData['HostComParaName']);
    }
}
