<?php

namespace Tests\Feature\PatVisit;

use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\CIUnitTestCase;

class PatVisitUpdateTest extends CIUnitTestCase
{
    use FeatureTestTrait;
    protected $endpoint = 'api/patvisit';

    /**
     * Test: Update patient visit successfully
     */
    public function testUpdatePatientVisitSuccess()
    {
        // Sesuaikan nilai ID dengan data di database test kamu
        $payload = [
            'InternalPVID' => 1,
            'PVID'         => 'DV0001',
            'EpisodeID'    => 'EPI001',
            'PatDiag' => [
                'DiagCode' => 'A02',
                'DiagName' => 'Dysentery'
            ],
            'PatVisitADT' => [
                'LocationID' => 12,
                'AdmitDate'  => date('Y-m-d H:i:s')
            ]
        ];

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

        // Pastikan response sukses
        $response->assertStatus(201);

        // Periksa fragment JSON
        $response->assertJSONFragment([
            'status'  => 'success',
            'message' => 'Data updated successfully',
        ]);

        // Pastikan response mengandung data yang sesuai
        $json = json_decode($response->getJSON(), true);
        $this->assertArrayHasKey('data', $json);
        $this->assertEquals('DV0001', $json['data']);
    }

    /**
     * Test: Update patient visit with invalid or missing ID
     */
    public function testUpdatePatientVisitInvalidId()
    {
        // InternalPVID tidak ada
        $payload = [
            'EpisodeID' => 'EPI002',
            'PatDiag'   => ['DiagCode' => 'B01', 'DiagName' => 'Flu']
        ];

        $response = $this->withBodyFormat('json')->call('patch', $this->endpoint, $payload);
        // Karena ID tidak ada → 500 Bad Request
        $response->assertStatus(500);

        $response->assertJSONFragment([
            'status'  => '500'
        ]); 
    }

    /**
     * Test: Update patient visit throws exception 
     */
    public function testUpdatePatientVisitThrowsException()
    {
        $payload = [
            'InternalPVID' => 'zehahahaha',
            'PVID'         => 'DV0001',
            'EpisodeID'    => 'EPI001',
            'PatDiag' => [
                'DiagCode' => 'A02',
                'DiagName' => 'Dysentery'
            ],
            'PatVisitADT' => [
                'LocationID' => 12,
                'AdmitDate'  => date('Y-m-d H:i:s')
            ]
        ];

        $response = $this->withBodyFormat('json')->call('patch', $this->endpoint, $payload);
        $response->assertStatus(400);
    }

    /**
     * Test: Update patient visit with []
     */
    public function testUpdatePatientVisitInvalidInput()
    {
        $payload = [];

        $response = $this->withBodyFormat('json')->call('patch', $this->endpoint, $payload);
        $response->assertStatus(500);
    }

}
