<?php

namespace Tests\Feature\Organization;

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

class AccountPatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    protected string $endpoint = 'api/organization/account';
    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 createAccount(array $data = []): int
    {
        $payload = array_merge([
            'AccountName' => 'Account ' . 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 fetchAccount(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 testPartialUpdateAccountSuccess()
    {
        $id = $this->createAccount();

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

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

        $account = $this->fetchAccount($id);
        $this->assertEquals('Updated Account', $account['AccountName']);
        $this->assertEquals($id, $account['AccountID']);
    }

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

        $patch->assertStatus(404);
    }

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateAccountEmptyPayload()
    {
        $id = $this->createAccount();

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdateAccountSingleField()
    {
        $id = $this->createAccount(['AccountName' => 'Original Name']);

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

        $patch->assertStatus(200);
        $account = $this->fetchAccount($id);

        $this->assertEquals('New Name', $account['AccountName']);
    }
}
