<?php

namespace Tests\Feature\Organization;

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

class DepartmentPatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

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

    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 createDepartment(array $data = []): array
    {
        $payload = array_merge([
            'DepartmentCode' => 'DEPT_' . uniqid(),
            'DepartmentName' => 'Test Department ' . uniqid(),
        ], $data);

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

        if ($response->getStatusCode() !== 201) {
            $this->markTestSkipped('Failed to create test department');
        }
        $decoded = json_decode($response->getJSON(), true);
        return $decoded['data'] ?? [];
    }

    public function testPartialUpdateDepartmentSuccess()
    {
        $dept = $this->createDepartment();
        $id = $dept['DepartmentID'];

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

        $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 Department', $showData['DepartmentName']);
        $this->assertEquals($dept['DepartmentCode'], $showData['DepartmentCode']);
    }

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

        $this->assertTrue(in_array($patch->getStatusCode(), [404, 400, 201]));
    }

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

        $this->assertTrue(in_array($patch->getStatusCode(), [404, 400, 201]));
    }

    public function testPartialUpdateDepartmentEmptyPayload()
    {
        $dept = $this->createDepartment();
        $id = $dept['DepartmentID'];

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateDepartmentSingleField()
    {
        $dept = $this->createDepartment();
        $id = $dept['DepartmentID'];

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

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

        $this->assertNotEquals($dept['DepartmentCode'], $showData['DepartmentCode']);
        $this->assertEquals($dept['DepartmentName'], $showData['DepartmentName']);
    }
}
