package servicerequest

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

// TODO: Sesuaikan dengan payload internal API ServiceRequest
func MapToInternalAPI(dbData *ServiceRequestDB, orgID string) map[string]interface{} {
	waktu := time.Now()
	if dbData.TglOrder.Valid {
		waktu = dbData.TglOrder.Time
	}
	payload := map[string]interface{}{
		"servicerequest_id": fmt.Sprintf("%d", dbData.IdxOrder),
		"encounter_id":      fmt.Sprintf("%d", dbData.IdxDaftar),
		"patient_id":        dbData.NoMR.String,
		"code":              dbData.KdOrder.String,
		"authored_on":       waktu.Format(time.RFC3339),
	}
	return payload
}

func MapToSyncLog(idx int64, fhirID string, reqPayload interface{}, respBody []byte, status string, errMsg string) ServiceRequestSyncLog {
	reqBytes, _ := json.MarshalIndent(reqPayload, "", "  ")
	return ServiceRequestSyncLog{
		IdxOrder:         idx,
		ServiceRequestID: fhirID,
		RequestPayload:   string(reqBytes),
		ResponsePayload:  string(respBody),
		Status:           status,
		ErrorMessage:     errMsg,
	}
}

func MapRadiologyToInternalAPI(dbData *ServiceRequestRadDB) map[string]interface{} {
	var parsedData ServiceRequestJson
	_ = json.Unmarshal([]byte(dbData.JsonData.String), &parsedData)

	categoryCode := ""
	categoryDisplay := ""
	if len(parsedData.Category) > 0 && len(parsedData.Category[0].Coding) > 0 {
		categoryCode = parsedData.Category[0].Coding[0].Code
		categoryDisplay = parsedData.Category[0].Coding[0].Display
	}

	codeVal := ""
	codeDisplay := ""
	if len(parsedData.Code.Coding) > 0 {
		codeVal = parsedData.Code.Coding[0].Code
		codeDisplay = parsedData.Code.Coding[0].Display
	}

	requesterID := dbData.RequesterID.String

	// Ambil dari DB terlebih dahulu, fallback ke JSON data jika kosong
	performerID := dbData.PerformerID.String
	if performerID == "" && len(parsedData.Performer) > 0 {
		performerID = parsedData.Performer[0].Reference
		if parts := strings.Split(performerID, "/"); len(parts) > 1 {
			performerID = parts[len(parts)-1]
		}
	}

	status := parsedData.Status
	if status == "" {
		status = "active" // Fallback jika kosong
	}

	intent := parsedData.Intent
	if intent == "" {
		intent = "order" // Fallback jika kosong
	}

	return map[string]interface{}{
		"patient_id":       dbData.PatientIHS.String,
		"patient_name":     dbData.PatientName.String,
		"encounter_id":     dbData.EncounterID.String,
		"status":           status,
		"intent":           intent,
		"category_code":    categoryCode,
		"category_display": categoryDisplay,
		"code":             codeVal,
		"display":          codeDisplay,
		"requester_id":     requesterID,
		"performer_id":     performerID,
		"authored_on":      parsedData.AuthoredOn,
	}
}
