<?php

namespace Tests\Feature\User;

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

class UserPatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    protected string $token;
    protected string $endpoint = 'api/user';

    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 createUser(array $data = []): array
    {
        $payload = array_merge([
            'UserCode' => 'USR_' . uniqid(),
            'UserName' => 'Test User ' . uniqid(),
            'Email' => 'user_' . uniqid() . '@test.com',
        ], $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 testPartialUpdateUserSuccess()
    {
        $user = $this->createUser();
        $id = $user['UserID'];

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

        $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 User', $showData['UserName']);
        $this->assertEquals($user['UserCode'], $showData['UserCode']);
    }

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

        $patch->assertStatus(404);
    }

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateUserEmptyPayload()
    {
        $user = $this->createUser();
        $id = $user['UserID'];

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateUserSingleField()
    {
        $user = $this->createUser();
        $id = $user['UserID'];

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

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

        $this->assertNotEquals($user['UserCode'], $showData['UserCode']);
        $this->assertEquals($user['UserName'], $showData['UserName']);
    }
}
