<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class LisController extends Controller
{
    /**
     * Alamat IP dan port dari service Python/Flask.
     * Sebaiknya diletakkan di file .env
     * LIS_SERVICE_URL=http://127.0.0.1:5000
     */
    protected $lisServiceUrl;

    public function __construct()
    {
        // Mengambil URL service dari file .env, dengan fallback default
        $this->lisServiceUrl = env('LIS_SERVICE_URL', 'http://localhost:5000');
    }

    /**
     * Mengirim perintah untuk mendaftarkan tes pasien baru ke GeneXpert.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function registerPatient(Request $request)
    {
        // Validasi input dari request (sangat direkomendasikan)
        $validatedData = $request->validate([
            'patient_name' => 'required|string|max:100',
            'patient_id'   => 'required|string|max:50',
            'sample_id'    => 'required|string|max:50',
            'test_code'    => 'required|string|max:20',
            'test_name'    => 'sometimes|string|max:50',
            'dob'          => 'sometimes|date_format:Ymd',
            'gender'       => 'sometimes|string|in:M,F,O,U',
        ]);

        // Membangun payload sesuai format yang diharapkan oleh app.py
        $payload = [
            'command' => 'register_patient',
            'data' => $validatedData,
        ];

        try {
            // Mengirim request POST ke service Python
            $response = Http::timeout(30) // Set timeout 30 detik
                ->post($this->lisServiceUrl . '/command', $payload);

            // Cek jika request gagal di level HTTP
            if ($response->failed()) {
                Log::error('Gagal terhubung ke LIS service saat registrasi.', [
                    'status' => $response->status(), 
                    'body' => $response->body()
                ]);
                return response()->json([
                    'error' => 'Tidak dapat terhubung ke LIS service.',
                    'details' => $response->body()
                ], 503); // Service Unavailable
            }

            // Mengembalikan response dari service Python ke client
            return response()->json($response->json(), $response->status());

        } catch (\Illuminate\Http\Client\ConnectionException $e) {
            Log::error('Koneksi ke LIS service gagal.', ['exception' => $e->getMessage()]);
            return response()->json(['error' => 'Koneksi ke LIS service gagal.'], 504); // Gateway Timeout
        }
    }

    /**
     * Mengirim perintah untuk meminta ulang hasil tes berdasarkan Sample ID.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function requestResult(Request $request)
    {
        // Validasi input
        $validatedData = $request->validate([
            'sample_id' => 'required|string|max:50',
        ]);

        // Membangun payload
        $payload = [
            'command' => 'request_result',
            'data' => $validatedData,
        ];

        try {
            // Mengirim request POST ke service Python
            $response = Http::timeout(30)->post($this->lisServiceUrl . '/command', $payload);
            
            if ($response->failed()) {
                Log::error('Gagal terhubung ke LIS service saat meminta hasil.', [
                    'status' => $response->status(), 
                    'body' => $response->body()
                ]);
                return response()->json([
                    'error' => 'Tidak dapat terhubung ke LIS service.',
                    'details' => $response->body()
                ], 503);
            }

            return response()->json($response->json(), $response->status());

        } catch (\Illuminate\Http\Client\ConnectionException $e) {
            Log::error('Koneksi ke LIS service gagal.', ['exception' => $e->getMessage()]);
            return response()->json(['error' => 'Koneksi ke LIS service gagal.'], 504);
        }
    }
}
