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

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

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

	erc "simrs-vx/internal/domain/references/common"
	ere "simrs-vx/internal/domain/references/encounter"

	ec "simrs-vx/internal/domain/main-entities/chemo"
	e "simrs-vx/internal/domain/main-entities/chemo-protocol"
)

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

	data.Chemo_Id = inputSrc.Chemo_Id
	data.Patient_Weight = inputSrc.Patient_Weight
	data.Patient_Height = inputSrc.Patient_Height
	data.Diagnoses = inputSrc.Diagnoses
	data.Interval = inputSrc.Interval
	data.Cycle = inputSrc.Cycle
	data.Series = inputSrc.Series
	data.StartDate = inputSrc.StartDate
	data.EndDate = inputSrc.EndDate
	data.Status_Code = inputSrc.Status_Code
	data.Patient_Id = inputSrc.Patient_Id
}

func getChemoEncounterReg(event *pl.Event) (*ec.Chemo, error) {
	pl.SetLogInfo(event, nil, "started", "DBReadChemoEncounterReg")
	data := ec.Chemo{}

	var tx = dg.I

	if err := tx.Model(&ec.Chemo{}).
		Joins(`LEFT JOIN "Encounter" "e" ON "e"."Id" = "Chemo"."Encounter_Id"`).
		Joins(`LEFT JOIN "Ambulatory" "a" ON "a"."Encounter_Id" = "e"."Id"`).
		Where(`"Chemo"."Status_Code" = ? AND "a"."Class_Code" = ?`, erc.DVCVerified, ere.ACCReg).
		Order("\"CreatedAt\" DESC").
		First(&data).
		Error; err != nil {
		if processedErr := pu.HandleReadError(err, event, source, nil, data); processedErr != nil {
			return nil, processedErr
		}
	}

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

func getChemoEncounter(encounterId *uint, event *pl.Event) (*ec.Chemo, error) {
	pl.SetLogInfo(event, encounterId, "started", "DBReadChemoEncounter")
	data := ec.Chemo{}

	var tx = dg.I

	if err := tx.Model(&ec.Chemo{}).
		Where(`"Encounter_Id" = ? AND "Status_Code"`, encounterId, erc.DVCVerified).
		Scopes(gh.Preload("Encounter.Ambulatory")).
		First(&data).
		Error; err != nil {
		if processedErr := pu.HandleReadError(err, event, source, nil, data); processedErr != nil {
			return nil, processedErr
		}
	}

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