<?php

namespace Tests\Feature\Organization;

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

class DisciplinePatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

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

    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 createDiscipline(array $data = []): int
    {
        $payload = array_merge([
            'DisciplineCode' => 'D' . strtoupper(bin2hex(random_bytes(1))),
            'DisciplineName' => 'Discipline ' . 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'];
    }

    private function fetchDiscipline(int $id): array
    {
        $response = $this->withHeaders($this->authHeaders())->call('get', "{$this->endpoint}/{$id}");
        $response->assertStatus(200);
        $decoded = json_decode($response->getJSON(), true);

        return $decoded['data'] ?? [];
    }

    public function testPartialUpdateDisciplineSuccess()
    {
        $id = $this->createDiscipline();

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

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

        $discipline = $this->fetchDiscipline($id);
        $this->assertEquals('Updated Discipline', $discipline['DisciplineName']);
        $this->assertEquals($id, $discipline['DisciplineID']);
    }

    public function testPartialUpdateDisciplineNotFound()
    {
        $patch = $this->withHeaders($this->authHeaders())
                      ->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/999999", ['DisciplineName' => 'Does not matter']);

        $patch->assertStatus(404);
    }

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateDisciplineEmptyPayload()
    {
        $id = $this->createDiscipline();

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateDisciplineSingleField()
    {
        $id = $this->createDiscipline(['DisciplineName' => 'Original Name']);

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

        $patch->assertStatus(200);
        $discipline = $this->fetchDiscipline($id);

        $this->assertEquals('New Name', $discipline['DisciplineName']);
    }
}
