<?php

namespace Tests\Feature;

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

class OrganizationControllerTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    protected $token;

    protected function setUp(): void
    {
        parent::setUp();

        // Generate JWT Token
        $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');
    }

    protected function callProtected($method, $path, $params = [])
    {
        return $this->withHeaders(['Cookie' => 'token=' . $this->token])
                    ->call($method, $path, $params);
    }

    private function createSite(array $overrides = []): array
    {
        $payload = array_merge([
            'SiteCode' => strtoupper(bin2hex(random_bytes(1))),
            'SiteName' => 'Partial Site ' . time(),
        ], $overrides);

        $result = $this->withHeaders(['Cookie' => 'token=' . $this->token])
                       ->withBody(json_encode($payload))
                       ->call('post', 'api/organization/site');
        $result->assertStatus(201);

        $decoded = json_decode($result->getJSON(), true);
        return [
            'id' => $decoded['data'],
            'code' => $payload['SiteCode'],
        ];
    }

    public function testSiteIndexReturnsSuccess()
    {
        $result = $this->callProtected('get', 'api/organization/site');
        $result->assertStatus(200);
        $json = $result->getJSON();
        $data = json_decode($json, true);
        $this->assertEquals('success', $data['status']);
    }

    public function testAccountIndexReturnsSuccess()
    {
        $result = $this->callProtected('get', 'api/organization/account');
        $result->assertStatus(200);
        $json = $result->getJSON();
        $data = json_decode($json, true);
        $this->assertEquals('success', $data['status']);
    }

    public function testDepartmentIndexReturnsSuccess()
    {
        $result = $this->callProtected('get', 'api/organization/department');
        $result->assertStatus(200);
        $json = $result->getJSON();
        $data = json_decode($json, true);
        $this->assertEquals('success', $data['status']);
    }

    public function testCreateSite()
    {
        $siteData = [
            'SiteCode' => 'S' . substr(time(), -5),
            'SiteName' => 'Test Site ' . time()
        ];

        $result = $this->withHeaders(['Cookie' => 'token=' . $this->token])
                       ->withBody(json_encode($siteData))
                       ->call('post', 'api/organization/site');

        $result->assertStatus(201);
        $json = $result->getJSON();
        $data = json_decode($json, true);

        $this->assertEquals('success', $data['status']);
        $this->assertIsInt($data['data']);
    }

    public function testCreateAccount()
    {
        $accountData = [
            'AccountName' => 'Test Account ' . time()
        ];

        $result = $this->withHeaders(['Cookie' => 'token=' . $this->token])
                       ->withBody(json_encode($accountData))
                       ->call('post', 'api/organization/account');

        $result->assertStatus(201);
        $json = $result->getJSON();
        $data = json_decode($json, true);

        $this->assertEquals('success', $data['status']);
        $this->assertIsInt($data['data']);
    }

    public function testCreateContainerDef()
    {
        $conData = [
            'SiteID' => 1,
            'ConCode' => 'C' . substr(time(), -2),
            'ConName' => 'Test Container ' . time()
        ];

        $result = $this->withHeaders(['Cookie' => 'token=' . $this->token])
                       ->withBody(json_encode($conData))
                       ->call('post', 'api/specimen/containerdef');

        $result->assertStatus(201);
        $json = $result->getJSON();
        $data = json_decode($json, true);

        $this->assertEquals('success', $data['status']);
        $this->assertIsInt($data['data']);
    }

    public function testPartialUpdateSiteKeepsOtherFields()
    {
        $site = $this->createSite(['SiteName' => 'Original Site']);
        $siteId = $site['id'];
        $siteCode = $site['code'];

        $updateResponse = $this->withHeaders(['Cookie' => 'token=' . $this->token])
                               ->withBodyFormat('json')
                               ->call('patch', 'api/organization/site/' . $siteId, ['SiteName' => 'Patched Site']);

        $updateResponse->assertStatus(200);
        $decoded = json_decode($updateResponse->getJSON(), true);
        $this->assertEquals('success', $decoded['status']);

        $show = $this->callProtected('get', 'api/organization/site/' . $siteId);
        $showData = json_decode($show->getJSON(), true)['data'];
        $this->assertEquals('Patched Site', $showData['SiteName']);
        $this->assertEquals($siteCode, $showData['SiteCode']);
    }
}
