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

import (
	"errors"

	e "simrs-vx/internal/domain/main-entities/antibiotic-in-use"
	emo "simrs-vx/internal/domain/main-entities/mcu-order"

	pl "simrs-vx/pkg/logger"

	"gorm.io/gorm"
)

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

	data.McuOrder_Id = inputSrc.McuOrder_Id
	data.AntibioticSrc_Id = inputSrc.AntibioticSrc_Id
	// data.ExaminationDate = inputSrc.ExaminationDate
}

func ValidateMcuOrderDoctor(input e.ReadDetailDto, doctorCode string, event *pl.Event, tx *gorm.DB) error {
	pl.SetLogInfo(event, input, "started", "ValidateMcuOrderDoctor")

	var mcuOrder emo.McuOrder
	if err := tx.First(&mcuOrder, input.Id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.New("mcu-order not found")
		}
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-get-fail",
			Detail: "Failed to get mcu-order",
			Raw:    err,
		}
		return pl.SetLogError(event, input)
	}

	if mcuOrder.Doctor_Code == nil || *mcuOrder.Doctor_Code != doctorCode {
		return errors.New("doctor is not authorized for this mcu-order")
	}

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