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

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

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

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

	e "simrs-vx/internal/domain/main-entities/chemo-plan"
	ep "simrs-vx/internal/domain/main-entities/chemo-protocol"
	es "simrs-vx/internal/domain/main-entities/soapi"
)

var now = time.Now()

func setDataCreate(input *ep.CreateDto) (data []e.ChemoPlan) {
	for _, c := range *input.ChemoPlans {
		data = append(data, e.ChemoPlan{
			Parent_Id:    input.Chemo_Id,
			Protocol_Id:  input.Id,
			SeriesNumber: c.SeriesNumber,
			CycleNumber:  c.CycleNumber,
			PlanDate:     c.PlanDate,
		})
	}
	return
}

func setDataUpdate(data *e.ChemoPlan) {
	data.RealizationDate = &now

	status := ere.SPCComplete
	data.Status = status
}

func setDatafail(input e.FailDto, data *e.ChemoPlan) {
	data.RealizationDate = nil
	data.Status = ere.SPCSchedule

	var reasons []e.FailReason

	if data.Reasons != nil {
		json.Unmarshal([]byte(*data.Reasons), &reasons)
	}

	reasons = append(reasons, e.FailReason{
		FailReason: input.Reasons,
		Date:       &now,
	})

	if b, err := json.Marshal(reasons); err == nil {
		jsonStr := string(b)
		data.Reasons = &jsonStr
	}
}

func getSoapiByEncounterId(encounterId uint, event *pl.Event) (*[]es.Soapi, error) {
	pl.SetLogInfo(event, encounterId, "started", "DBReadDetail")
	var data []es.Soapi

	var tx = dg.I

	if err := tx.
		Model(&es.Soapi{}).
		Where(`"Encounter_Id" = ?`, encounterId).
		Find(&data).Error; err != nil {
		if processedErr := pu.HandleReadError(err, event, source, encounterId, data); processedErr != nil {
			return nil, processedErr
		}
	}

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