<?php

namespace Tests\Feature\PatVisit;

use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\CIUnitTestCase;
use Tests\Support\Traits\CreatesPatients;

class PatVisitADTPatchTest extends CIUnitTestCase
{
    use FeatureTestTrait;
    use CreatesPatients;

    protected string $endpoint = 'api/patvisitadt';

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

    private function createPatVisitADT(array $data = []): array
    {
        $payload = array_merge([
            'InternalPID' => $this->createTestPatient(),
            'ADTCode' => 'A01',
            'LocationID' => '1',
        ], $data);

        $response = $this->withBodyFormat('json')->call('post', $this->endpoint, $payload);
        $response->assertStatus(201);
        $decoded = json_decode($response->getJSON(), true);
        return $decoded['data'];
    }

    public function testPartialUpdatePatVisitADTSuccess()
    {
        $adt = $this->createPatVisitADT();
        $id = $adt['ADTID'];

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

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

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

        $this->assertEquals('A02', $showData['ADTCode']);
        $this->assertEquals($adt['LocationID'], $showData['LocationID']);
    }

    public function testPartialUpdatePatVisitADTNotFound()
    {
        $patch = $this->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/999999", ['ADTCode' => 'A02']);

        $patch->assertStatus(404);
    }

    public function testPartialUpdatePatVisitADTInvalidId()
    {
        $patch = $this->withBodyFormat('json')
                      ->call('patch', "{$this->endpoint}/invalid", ['ADTCode' => 'A02']);

        $patch->assertStatus(400);
    }

    public function testPartialUpdatePatVisitADTEmptyPayload()
    {
        $adt = $this->createPatVisitADT();
        $id = $adt['ADTID'];

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

        $patch->assertStatus(400);
    }

    public function testPartialUpdatePatVisitADTSingleField()
    {
        $adt = $this->createPatVisitADT();
        $id = $adt['ADTID'];

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

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

        $this->assertEquals('A03', $showData['ADTCode']);
        $this->assertEquals($adt['LocationID'], $showData['LocationID']);
    }
}
