<?php

namespace Tests\Feature\Organization;

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

class HostAppPatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

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

    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 createHostApp(array $data = []): array
    {
        $payload = array_merge([
            'HostAppName' => 'Test HostApp ' . uniqid(),
            'SiteID' => null,
        ], $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(['HostAppID' => $id], $payload);
    }

    public function testPartialUpdateHostAppSuccess()
    {
        $app = $this->createHostApp();
        $id = $app['HostAppID'];

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

        $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 HostApp', $showData['HostAppName']);
        $this->assertEquals($app['SiteID'], $showData['SiteID']);
    }

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

        $patch->assertStatus(404);
    }

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateHostAppEmptyPayload()
    {
        $app = $this->createHostApp();
        $id = $app['HostAppID'];

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateHostAppSingleField()
    {
        $app = $this->createHostApp();
        $id = $app['HostAppID'];

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

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

        $this->assertNotEquals($app['SiteID'], $showData['SiteID']);
        $this->assertEquals($app['HostAppName'], $showData['HostAppName']);
    }
}
