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

import (
	e "simrs-vx/internal/domain/main-entities/medication"
	emi "simrs-vx/internal/domain/main-entities/medication-item"
	emid "simrs-vx/internal/domain/main-entities/medication-item-dist"
	umi "simrs-vx/internal/use-case/main-use-case/medication-item"
	umid "simrs-vx/internal/use-case/main-use-case/medication-item-dist"

	pl "simrs-vx/pkg/logger"
	pu "simrs-vx/pkg/use-case-helper"

	dg "github.com/karincake/apem/db-gorm-pg"

	"gorm.io/gorm"
)

func setData[T *e.CreateDto | *e.UpdateDto](input T, data *e.Medication) {
	var inputSrc *e.CreateDto
	if inputT, ok := any(input).(*e.CreateDto); ok {
		inputSrc = inputT
	} else {
		inputTemp := any(input).(*e.UpdateDto)
		inputSrc = &inputTemp.CreateDto
	}

	data.Encounter_Id = inputSrc.Encounter_Id
	data.IssuedAt = inputSrc.IssuedAt
	data.Pharmacist_Code = inputSrc.Pharmacist_Code
	data.Status_Code = inputSrc.Status_Code
}

func createMedicationItemDist(medication_id *uint, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, nil, "started", "createMedicationItemDist")
	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	filterMI := emi.ReadListDto{FilterDto: emi.FilterDto{Medication_Id: medication_id, IsRedeemed: true}, Preloads: []string{"MedicineMix"}}
	medicationItemList, _, err := umi.ReadListData(filterMI, event, tx)
	if err != nil {
		return err
	}
	// Nurse id isn't set here because it will be set when medItemDist is consumed by the nurse who is logged in and performing the consume action, so it isn't needed here.
	for _, medicationItem := range medicationItemList {
		midCreate := emid.CreateDto{
			MedicationItem_Id: &medicationItem.Id,
			DateTime:          pu.GetTimeNow(),
			Remain:            medicationItem.Quantity,
		}
		if _, err := umid.CreateData(midCreate, event, tx); err != nil {
			return err
		}

	}

	pl.SetLogInfo(event, nil, "complete")
	return nil
}
