package encounter

import (
	"encoding/json"
	"fmt"
	"time"
)

// MapToInternalAPI memetakan data database menjadi payload untuk Internal API GoPrint
func MapToInternalAPI(dbData *PendaftaranDB, orgID string) map[string]interface{} {
	// 1. Penentuan status encounter
	status := "arrived"
	if dbData.Batal.Valid && dbData.Batal.String == "Y" {
		status = "cancelled"
	} else if dbData.KeluarPoly.Valid {
		status = "finished"
	} else if dbData.MasukPoly.Valid {
		status = "in-progress"
	}

	// 2. Format Period Waktu
	periodStart := time.Now()
	if dbData.MasukPoly.Valid {
		periodStart = dbData.MasukPoly.Time
	} else if dbData.JamReg.Valid {
		periodStart = dbData.JamReg.Time
	}

	// 3. Ekstrak Kelengkapan ID IHS
	patientIHS := dbData.NoMR.String // Fallback ke NoMR jika IHS tidak ada
	if dbData.PatientIHS.Valid && dbData.PatientIHS.String != "" {
		patientIHS = dbData.PatientIHS.String
	}
	practitionerIHS := ""
	if dbData.PractitionerIHS.Valid && dbData.PractitionerIHS.String != "" {
		practitionerIHS = dbData.PractitionerIHS.String
	}
	locationIHS := ""
	if dbData.LocationIHS.Valid && dbData.LocationIHS.String != "" {
		locationIHS = dbData.LocationIHS.String
	}

	// 4. Bangun Payload Internal API
	payload := map[string]interface{}{
		"encounter_id":      fmt.Sprintf("%d", dbData.IdxDaftar),
		"organization_id":   orgID,
		"patient_id":        patientIHS,
		"patient_name":      "Pasien " + patientIHS, // Nama fallback untuk lolos validasi usecase
		"practitioner_id":   practitionerIHS,
		"practitioner_name": "Tenaga Kesehatan", // Nama fallback
		"location_id":       locationIHS,
		"location_name":     "Poli Faskes", // Nama fallback
		"status":            status,
		"class":             "AMB",
		"period_start":      periodStart.Format(time.RFC3339),
	}

	if dbData.KeluarPoly.Valid {
		payload["period_end"] = dbData.KeluarPoly.Time.Format(time.RFC3339)
	}

	return payload
}

// MapToSyncLog membuat struktur data log histori untuk disimpan ke tabel database
func MapToSyncLog(idxdaftar int64, encounterID string, reqPayload interface{}, respBody []byte, status string, errMsg string) EncounterSyncLog {
	reqBytes, _ := json.MarshalIndent(reqPayload, "", "  ") // Indent agar JSON mudah dibaca saat dibuka di DB/Adminer
	return EncounterSyncLog{
		IdxDaftar:       idxdaftar,
		EncounterID:     encounterID,
		RequestPayload:  string(reqBytes),
		ResponsePayload: string(respBody),
		Status:          status,
		ErrorMessage:    errMsg,
	}
}
