/*
DESCRIPTION:
Any functions that are used internally by the use-case
*/
package internal_reference

import (
	"encoding/json"
	eir "simrs-vx/internal/domain/main-entities/internal-reference"
	erc "simrs-vx/internal/domain/references/common"
	"strconv"

	e "simrs-vx/internal/domain/main-entities/encounter"

	etph "simrs-vx/internal/domain/simgos-entities/t-pemeriksaan-hist"
	etp "simrs-vx/internal/domain/simgos-entities/t-pendaftaran"

	esync "simrs-vx/internal/domain/sync-entities/internal-reference"
	esyncLog "simrs-vx/internal/domain/sync-entities/log"
)

func setCreateDataSimgos(input e.Encounter, data *etp.TPendaftaran) (hist []etph.TPemeriksaanHist) {
	if enc := input.InternalReferences; enc != nil {
		for i, ref := range *enc {
			hist = append(hist, etph.TPemeriksaanHist{
				Idxdaftar:       &data.Idxdaftar,
				Kdpoly:          stringtouint(*ref.Unit_Code),
				DokterPengonsul: stringtouint(*ref.SrcDoctor_Code),
				DokterPenerima:  stringtouint(*ref.Doctor_Code),
			})

			// set user konsul
			if n := input.Responsible_Nurse; n != nil {
				if emp := n.Employee; emp != nil {
					if u := emp.User; u != nil {
						hist[i].UserKonsul = &u.Name
					}
				}
			}

			// setaktif
			aktif := uint16(1)
			hist[i].StAktif = &aktif
		}
	}
	return
}

func setUpdateApproveDataSimgos(input e.ApproveCancelUnitDto, data *etph.TPemeriksaanHist) {
	data.DokterPenerima = stringtouint(*input.Dst_Doctor_Code)
	data.StartKonsul = &now
	data.UserPenerima = &input.User_Name
	data.MasukPoly = data.StartKonsul
	return
}

func setUpdateCancelDataSimgos(input e.ApproveCancelUnitDto, data *etph.TPemeriksaanHist) {
	data.UserBatal = &input.User_Name
	data.TglBatal = &now

	aktif := uint16(0)
	data.StAktif = &aktif

	return
}

func setDataSimxLog(input *esyncLog.SimxLogDto) (data esync.InternalReferenceSimxLog) {
	// encode to JSON
	jsonData, _ := json.MarshalIndent(input.Payload, "", "  ")
	jsonString := string(jsonData)

	var status erc.ProcessStatusCode
	if input.IsSuccess {
		status = erc.PSCSuccess
	} else {
		status = erc.PSCFailed
		if input.ErrMessage != nil {
			data.ErrMessage = input.ErrMessage
		}
	}

	data.Value = &jsonString
	data.Date = &now
	data.Status = status

	return
}

func setDataSimxLink(ir []eir.InternalReference, tph []etph.TPemeriksaanHist) (data []esync.InternalReferenceLink) {
	for i := range len(ir) {
		data = append(data, esync.InternalReferenceLink{
			Simx_Id:   ir[i].Id,
			Simgos_Id: tph[i].IdPemeriksaanHist,
		})
	}
	return
}

func stringtouint(v string) *uint {
	u, _ := strconv.Atoi(v)
	point := uint(u)
	return &point
}
