package imagingstudy

import (
	"encoding/json"
	"time"
)

// MapToInternalAPI memetakan data gabungan ke payload API Internal SatuSehat
func MapToInternalAPI(dbData *ImagingStudyDB, orgID string) map[string]interface{} {
	waktu := time.Now()
	if dbData.StartedDate.Valid {
		waktu = dbData.StartedDate.Time
	}

	procedureCode := dbData.Modality.String
	if procedureCode == "" {
		procedureCode = "DX" // Default ke "DX" jika modality kosong
	}

	payload := map[string]interface{}{
		"organization_id":    orgID,
		"accession_number":   dbData.AccessionNumber.String,
		"service_request_id": dbData.ServiceRequestID.String,
		"patient_id":         dbData.PatientIHS.String,
		"encounter_id":       dbData.EncounterIHS.String,
		"status":             "available",
		"started":            waktu.Format(time.RFC3339),
		"procedure_code":     procedureCode,
	}
	return payload
}

func MapToSyncLog(id string, fhirID string, reqPayload interface{}, respBody []byte, status string, errMsg string) SyncLog {
	reqBytes, _ := json.Marshal(reqPayload)
	return SyncLog{
		ImagingStudyID:  id,
		SatuSehatID:     fhirID,
		RequestPayload:  string(reqBytes),
		ResponsePayload: string(respBody),
		Status:          status,
		ErrorMessage:    errMsg,
	}
}
