package encounter

import (
	// std
	"errors"
	// external
	dg "github.com/karincake/apem/db-gorm-pg"
	gh "github.com/karincake/getuk"
	"gorm.io/gorm"

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

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

	e "simrs-vx/internal/domain/main-entities/encounter"
	er "simrs-vx/internal/domain/main-entities/rehab"
)

const ErrorReadFailed = "Database read failed"

func CreateData(input e.CreateDto, event *pl.Event, dbx ...*gorm.DB) (*e.Encounter, error) {
	pl.SetLogInfo(event, nil, "started", "DBCreate")

	data := e.Encounter{}
	setData(&input, &data)

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Create(&data).Error; err != nil {
		return nil, plh.HandleCreateError(input, event, err)
	}

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

func ReadListData(input e.ReadListDto, event *pl.Event, dbx ...*gorm.DB) ([]e.Encounter, *e.MetaDto, error) {
	if input.AuthInfo.User_Id == 0 {
		return nil, nil, plh.HandleListError(input, event, errors.New("user_id is required"))
	}

	pl.SetLogInfo(event, input, "started", "DBReadList")
	data := []e.Encounter{}
	pagination := gh.Pagination{}
	count := int64(0)
	meta := e.MetaDto{}

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}
	tx = tx.Model(&e.Encounter{})

	if input.AuthInfo.Doctor_Code != nil {
		tx.Where("\"Responsible_Doctor_Code\" = ?", *input.AuthInfo.Doctor_Code) //
	}

	if input.StartDate != nil && input.EndDate != nil {
		tx = tx.Where(
			"DATE(\"Encounter\".\"RegisteredAt\") >= DATE(?) AND DATE(\"Encounter\".\"RegisteredAt\") <= DATE(?)",
			input.StartDate,
			input.EndDate,
		)
	}

	if input.Patient_Identifier != nil {
		tx = tx.Joins("JOIN \"Patient\" ON \"Patient\".\"Id\" = \"Encounter\".\"Patient_Id\"").
			Joins("JOIN \"Person\" ON \"Person\".\"Id\" = \"Patient\".\"Person_Id\"").Where("\"Person\".\"Name\" ILIKE ? OR \"Patient\".\"Number\" = ?", "%"+*input.Patient_Identifier+"%", *input.Patient_Identifier)
	}

	// TODO: getuk lib need to be updated to support this
	if input.Status_Code != nil {
		tx = tx.Where("\"Encounter\".\"Status_Code\" = ?", *input.Status_Code)
	}

	if input.Unit_Code != nil {
		tx = tx.Where("\"Encounter\".\"Unit_Code\" = ?", *input.Unit_Code)
	}

	if input.PaymentMethod_Code != nil {
		tx = tx.Where("\"Encounter\".\"PaymentMethod_Code\" = ?", *input.PaymentMethod_Code)
	}

	tx = tx.Scopes(gh.Preload(input.Includes)).
		Count(&count).
		Scopes(gh.Paginate(input, &pagination)).
		Order("\"CreatedAt\" DESC")

	// tx.Debug().Scopes(gh.Preload(input.Includes)).
	// 	Scopes(gh.Filter(input.FilterDto)).
	// 	Count(&count).
	// 	Scopes(gh.Paginate(input, &pagination)).
	// 	Order("\"CreatedAt\" DESC")

	if err := tx.Find(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, &meta, nil
		}
		return nil, nil, plh.HandleListError(input, event, err)
	}

	meta.Count = int(count)
	meta.PageNumber = pagination.PageNumber
	meta.PageSize = pagination.PageSize

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

func ReadDetailData(input e.ReadDetailDto, event *pl.Event, dbx ...*gorm.DB) (*e.Encounter, error) {
	pl.SetLogInfo(event, input, "started", "DBReadDetail")
	data := e.Encounter{}

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Scopes(gh.Preload(input.Includes)).First(&data, input.Id).Error; err != nil {
		if processedErr := pu.HandleReadError(err, event, source, input.Id, data); processedErr != nil {
			return nil, processedErr
		}
	}

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

func UpdateData(input e.UpdateDto, data *e.Encounter, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, data, "started", "DBUpdate")
	setDataUpdate(input, data)

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Save(&data).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-update-fail",
			Detail: "Database update failed",
			Raw:    err,
		}
		return pl.SetLogError(event, input)
	}

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

func DeleteData(data *e.Encounter, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, data, "started", "DBDelete")
	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Delete(&data).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-delete-fail",
			Detail: "Database delete failed",
			Raw:    err,
		}
		return pl.SetLogError(event, data)
	}

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

func updateDischargeData(input e.DischargeDto, data *e.Encounter, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, data, "started", "DBUpdateDischarge")
	setDataDischarge(input, data)

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Save(&data).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-update-fail",
			Detail: "Database update failed",
			Raw:    err,
		}
		return pl.SetLogError(event, input)
	}

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

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

	var data e.Encounter
	if err := tx.Where("\"Id\" = ?", encounter_id).First(&data).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-get-fail",
			Detail: "Database get failed",
			Raw:    err,
		}
		return false
	}

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

func UpdateStatusData(input e.UpdateStatusDto, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, input, "started", "DBUpdateStatus")

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Model(&e.Encounter{}).
		Where("\"Id\" = ?", input.Id).
		Update("Status_Code", input.StatusCode).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "update-fail",
			Detail: "Failed to update status code",
			Raw:    err,
		}
		return pl.SetLogError(event, input)
	}

	return nil
}

func UpdateDischargeMethod(input e.SwitchUnitDto, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, input, "started", "DBUpdateDischargeMethod")
	dischargeCode := setDischargeMethodCode(*input.PolySwitchCode)

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Model(&e.Encounter{}).
		Where("\"Id\" = ?", input.Id).
		Update("Discharge_Method_Code", dischargeCode).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "update-fail",
			Detail: "Failed to update discharge method code",
			Raw:    err,
		}
		return pl.SetLogError(event, input)
	}

	return nil
}

func updateCheckInData(input e.CheckinDto, data *e.Encounter, event *pl.Event, dbx ...*gorm.DB) error {
	pl.SetLogInfo(event, data, "started", "DBUpdateCheckin")
	setDataCheckIn(input, data)

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Save(&data).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "data-update-fail",
			Detail: "Database update failed",
			Raw:    err,
		}
		return pl.SetLogError(event, input)
	}

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

func getLatestRehabData(i e.CreateDto, event *pl.Event) (recentRehabData *er.Rehab, err error) {
	pl.SetLogInfo(event, nil, "started", "DBGetLatestRehab")

	var (
		tx = dg.I
	)

	err = tx.
		Joins("JOIN \"Encounter\" ON \"Encounter\".\"Id\" = \"Rehab\".\"Encounter_Id\"").
		Where("\"Encounter\".\"Patient_Id\" = ?", i.Patient_Id).
		Order("\"CreatedAt\" DESC").
		First(&recentRehabData).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}

		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "read-recentRehab-fail",
			Detail: ErrorReadFailed,
			Raw:    err,
		}
		return nil, pl.SetLogError(event, i)
	}

	return
}

func verifyAllocatedVisitCount(i e.CreateDto, event *pl.Event) (e.Encounter, bool, error) {
	pl.SetLogInfo(event, nil, "started", "DBGetRecentEncounterAdm")

	var (
		tx                 = dg.I
		recentEncounterAdm e.Encounter
		valid              = true
	)

	err := tx.
		Scopes(gh.Preload("RehabChildren,Rehab,Responsible_Doctor")).
		Joins("JOIN \"Rehab\" ON \"Rehab\".\"Encounter_Id\" = \"Encounter\".\"Id\"").
		Where("\"Encounter\".\"Patient_Id\" = ?", i.Patient_Id).
		Where("\"Rehab\".\"VisitMode_Code\" = ?", ere.VMCAdm).
		Order("\"CreatedAt\" DESC").
		First(&recentEncounterAdm).Error
	if err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "read-recentEncounter-fail",
			Detail: "Database read failed",
			Raw:    err,
		}
		return e.Encounter{}, false, pl.SetLogError(event, i)
	}

	// validate count rehab children
	if recentEncounterAdm.RehabChildren != nil && len(*recentEncounterAdm.RehabChildren) > 0 {
		valid = len(*recentEncounterAdm.RehabChildren) < *recentEncounterAdm.Rehab.AllocatedVisitCount
	}

	return recentEncounterAdm, valid, nil
}

func updateEncounterApproveSwitchUnit(input e.ApproveCancelUnitDto, event *pl.Event, dbx ...*gorm.DB) (err error) {
	pl.SetLogInfo(event, nil, "started", "DBCreate")

	var tx *gorm.DB
	if len(dbx) > 0 {
		tx = dbx[0]
	} else {
		tx = dg.I
	}

	if err := tx.Model(&e.Encounter{}).
		Where("\"Id\" = ?", input.Id).
		Updates(map[string]interface{}{
			"Responsible_Doctor_Code": input.Dst_Doctor_Code,
			"Responsible_Nurse_Code":  input.Nurse_Code,
		}).Error; err != nil {
		event.Status = "failed"
		event.ErrInfo = pl.ErrorInfo{
			Code:   "update-fail",
			Detail: "Failed to update encounter approve switch unit",
			Raw:    err,
		}
		return pl.SetLogError(event, input)
	}

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