<?php

namespace Tests\Feature\PatVisit;

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

class PatVisitCreateTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    protected $endpoint = 'api/patvisit';

    /**
     * Test: Create patient visit with valid data
     */
    public function testCreatePatientVisitSuccess()
    {
        $payload = [
            "InternalPID"=> "1",
            "EpisodeID"=> null,
            "PatDiag"=> [
                "DiagCode"=> null,
                "Diagnosis"=> null
            ],
            "PatVisitADT"=> [
                "ADTCode"=> "A01",
                "LocationID"=> "1",
                "AttDoc"=> "1",
                "RefDoc"=> "1",
                "AdmDoc"=> "1",
                "CnsDoc"=> "1"
            ],
            "PatAtt"=> []
        ];

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

        // Pastikan status 201 (created)
        $response->assertStatus(201);

        // Pastikan JSON mengandung status success dan message yang benar
        $response->assertJSONFragment([
            'status'  => 'success',
            'message' => 'Data created successfully'
        ]);

        $json = json_decode($response->getJSON(), true);

        // Pastikan struktur data yang dikembalikan benar
        $this->assertArrayHasKey('data', $json);
        $this->assertArrayHasKey('PVID', $json['data']);
        $this->assertArrayHasKey('InternalPVID', $json['data']);
    }

    /**
     * Test: Create patient visit with invalid (empty) data
     */
    public function testCreatePatientVisitInvalidInput()
    {
        $payload = [];
        // Kirim data kosong
        $response = $this->withBodyFormat('json')->call('post', $this->endpoint, $payload);

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

    // /**
    //  * Test: Simulate internal server error (trigger exception manually)
    //  */
    public function testCreatePatientVisitThrowsException()
    {
        // Gunakan input yang memicu exception, misalnya EpisodeID panjang tak wajar
        $payload = [
            'InternalPID' => 1,
            'EpisodeID'   => str_repeat('X', 300) // melebihi batas kolom (jika <255)
        ];

        $response = $this->post($this->endpoint , $payload);

        $response->assertStatus(500);
    }

}
