<?php

namespace Tests\Feature\PatVisit;

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

class PatVisitDeleteTest extends CIUnitTestCase
{
    use FeatureTestTrait;
    use CreatesPatients;

    protected $endpoint = 'api/patvisit';

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

    /**
     * Test: Delete patient visit successfully (soft delete)
     */
    public function testDeletePatientVisitSuccess()
    {
        // Create a visit first to delete
        $createPayload = [
            "InternalPID"=> $this->createTestPatient(),
            "EpisodeID"=> "TEST001",
            "PatVisitADT"=> [
                "ADTCode"=> "A01",
                "LocationID"=> "1"
            ]
        ];

        $createResponse = $this->withBodyFormat('json')->call('post', $this->endpoint, $createPayload);
        $createResponse->assertStatus(201);
        
        $json = json_decode($createResponse->getJSON(), true);
        $internalPVID = $json['data']['InternalPVID'];

        // Now delete it
        $deletePayload = [
            'InternalPVID' => $internalPVID
        ];

        $response = $this->withBodyFormat('json')->call('delete', $this->endpoint, $deletePayload);

        $response->assertStatus(200);
        $response->assertJSONFragment([
            'status'  => 'success',
            'message' => 'Data deleted successfully'
        ]);
    }

    /**
     * Test: Delete patient visit with missing ID
     */
    public function testDeletePatientVisitMissingId()
    {
        $payload = [];

        $response = $this->withBodyFormat('json')->call('delete', $this->endpoint, $payload);
        $response->assertStatus(400);
        $response->assertJSONFragment([
            'status'  => 'error',
            'message' => 'Invalid or missing ID'
        ]);
    }

    /**
     * Test: Delete patient visit with invalid ID (non-numeric)
     */
    public function testDeletePatientVisitInvalidId()
    {
        $payload = [
            'InternalPVID' => 'invalid'
        ];

        $response = $this->withBodyFormat('json')->call('delete', $this->endpoint, $payload);
        $response->assertStatus(400);
        $response->assertJSONFragment([
            'status'  => 'error',
            'message' => 'Invalid or missing ID'
        ]);
    }

    /**
     * Test: Delete patient visit with non-existent ID
     */
    public function testDeletePatientVisitNotFound()
    {
        $payload = [
            'InternalPVID' => 999999 // Non-existent visit
        ];

        $response = $this->withBodyFormat('json')->call('delete', $this->endpoint, $payload);
        $response->assertStatus(404);
        $response->assertJSONFragment([
            'status'  => 'error',
            'message' => 'Visit not found'
        ]);
    }

}
