package mcuorder

import (
	"errors"
	"strconv"

	e "simrs-vx/internal/domain/main-entities/mcu-order"

	ue "simrs-vx/internal/use-case/main-use-case/encounter"

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

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

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

	"gorm.io/gorm"
)

const source = "mcu-order"

func Create(input e.CreateDto) (*d.Data, error) {
	data := e.McuOrder{}

	event := pl.Event{
		Feature: "Create",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "create")

	err := dg.I.Transaction(func(tx *gorm.DB) error {
		mwRunner := newMiddlewareRunner(&event, tx)
		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err := mwRunner.RunCreateMiddleware(createPreMw, &input, &data); err != nil {
			return err
		}

		// check if encounter is done
		if ue.IsDone(*input.Encounter_Id, &event, tx) {
			return errors.New("encounter is already done")
		}

		if !input.AuthInfo.IsDoctor() {
			event.Status = "failed"
			event.ErrInfo = pl.ErrorInfo{
				Code:   "auth-forbidden",
				Detail: "user position is not allowed",
				Raw:    errors.New("authentication failed"),
			}
			return pl.SetLogError(&event, input)
		}

		input.Doctor_Code = input.AuthInfo.Doctor_Code

		if resData, err := CreateData(input, &event, tx); err != nil {
			return err
		} else {
			data = *resData
		}

		mwRunner.setMwType(pu.MWTPost)
		// Run post-middleware
		if err := mwRunner.RunCreateMiddleware(createPostMw, &input, &data); err != nil {
			return err
		}

		pl.SetLogInfo(&event, nil, "complete")

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &d.Data{
		Meta: d.II{
			"source":    source,
			"structure": "single-data",
			"status":    "created",
		},
		Data: data.ToResponse(),
	}, nil
}

func ReadList(input e.ReadListDto) (*d.Data, error) {
	var data *e.McuOrder
	var dataList []e.McuOrder
	var metaList *e.MetaDto
	var err error

	event := pl.Event{
		Feature: "ReadList",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "readList")

	err = dg.I.Transaction(func(tx *gorm.DB) error {
		mwRunner := newMiddlewareRunner(&event, tx)
		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err := mwRunner.RunReadListMiddleware(readListPreMw, &input, data); err != nil {
			return err
		}

		if dataList, metaList, err = ReadListData(input, &event, tx); err != nil {
			return err
		}

		mwRunner.setMwType(pu.MWTPost)
		// Run post-middleware
		if err := mwRunner.RunReadListMiddleware(readListPostMw, &input, data); err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &d.Data{
		Meta: d.IS{
			"source":              source,
			"structure":           "list-data",
			"status":              "fetched",
			"page_number":         strconv.Itoa(metaList.PageNumber),
			"page_size":           strconv.Itoa(metaList.PageSize),
			"record_totalCount":   strconv.Itoa(metaList.Count),
			"record_currentCount": strconv.Itoa(len(dataList)),
		},
		Data: e.ToResponseList(dataList),
	}, nil
}

func ReadDetail(input e.ReadDetailDto) (*d.Data, error) {
	var data *e.McuOrder
	var err error

	event := pl.Event{
		Feature: "ReadDetail",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "readDetail")

	err = dg.I.Transaction(func(tx *gorm.DB) error {
		mwRunner := newMiddlewareRunner(&event, tx)
		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err := mwRunner.RunReadDetailMiddleware(readDetailPreMw, &input, data); err != nil {
			return err
		}

		if data, err = ReadDetailData(input, &event, tx); err != nil {
			return err
		}

		mwRunner.setMwType(pu.MWTPost)
		// Run post-middleware
		if err := mwRunner.RunReadDetailMiddleware(readDetailPostMw, &input, data); err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &d.Data{
		Meta: d.IS{
			"source":    source,
			"structure": "single-data",
			"status":    "fetched",
		},
		Data: data.ToResponse(),
	}, nil
}

func Update(input e.UpdateDto) (*d.Data, error) {
	rdDto := e.ReadDetailDto{Id: input.Id}
	var data *e.McuOrder
	var err error

	event := pl.Event{
		Feature: "Update",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "update")

	err = dg.I.Transaction(func(tx *gorm.DB) error {
		pl.SetLogInfo(&event, rdDto, "started", "DBReadDetail")
		if data, err = ReadDetailData(rdDto, &event, tx); err != nil {
			return err
		}

		if data.IsCompleted() {
			return errors.New("data already completed")
		}

		mwRunner := newMiddlewareRunner(&event, tx)
		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err := mwRunner.RunUpdateMiddleware(readDetailPreMw, &rdDto, data); err != nil {
			return err
		}

		if !input.AuthInfo.IsDoctor() {
			event.Status = "failed"
			event.ErrInfo = pl.ErrorInfo{
				Code:   "auth-forbidden",
				Detail: "user position is not allowed",
				Raw:    errors.New("authentication failed"),
			}
			return pl.SetLogError(&event, input)
		}

		if !data.IsSameDoctor(input.AuthInfo.Doctor_Code) {
			event.Status = "failed"
			event.ErrInfo = pl.ErrorInfo{
				Code:   "auth-forbidden",
				Detail: "doctor is not the same as the data",
				Raw:    errors.New("authentication failed"),
			}
			return pl.SetLogError(&event, input)
		}

		input.Doctor_Code = input.AuthInfo.Doctor_Code

		if err := UpdateData(input, data, &event, tx); err != nil {
			return err
		}

		pl.SetLogInfo(&event, nil, "complete")

		mwRunner.setMwType(pu.MWTPost)
		// Run post-middleware
		if err := mwRunner.RunUpdateMiddleware(readDetailPostMw, &rdDto, data); err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &d.Data{
		Meta: d.IS{
			"source":    source,
			"structure": "single-data",
			"status":    "updated",
		},
		Data: data.ToResponse(),
	}, nil

}

func Delete(input e.DeleteDto) (*d.Data, error) {
	rdDto := e.ReadDetailDto{Id: input.Id}
	var data *e.McuOrder
	var err error

	event := pl.Event{
		Feature: "Delete",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "delete")

	err = dg.I.Transaction(func(tx *gorm.DB) error {
		pl.SetLogInfo(&event, rdDto, "started", "DBReadDetail")
		if data, err = ReadDetailData(rdDto, &event, tx); err != nil {
			return err
		}

		mwRunner := newMiddlewareRunner(&event, tx)
		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err := mwRunner.RunDeleteMiddleware(readDetailPreMw, &rdDto, data); err != nil {
			return err
		}

		if err := DeleteData(data, &event, tx); err != nil {
			return err
		}

		mwRunner.setMwType(pu.MWTPost)
		// Run post-middleware
		if err := mwRunner.RunDeleteMiddleware(readDetailPostMw, &rdDto, data); err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &d.Data{
		Meta: d.IS{
			"source":    source,
			"structure": "single-data",
			"status":    "deleted",
		},
		Data: data.ToResponse(),
	}, nil

}

func Submit(input e.ReadDetailDto) (*d.Data, error) {
	var data *e.McuOrder
	var err error

	event := pl.Event{
		Feature: "Process",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "process")

	err = dg.I.Transaction(func(tx *gorm.DB) error {
		data, err = ReadDetailData(input, &event, tx)
		if err != nil {
			return err
		}

		if data.IsNotNew() {
			event.Status = "failed"
			event.ErrInfo = pl.ErrorInfo{
				Code:   "data-state-mismatch",
				Detail: "prescription is not in new state",
				Raw:    errors.New("prescription is not in new state"),
			}
			return pl.SetLogError(&event, input)
		}

		data.Status_Code = erc.DSCSubmited
		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
	})

	if err != nil {
		return nil, err
	}

	return &d.Data{
		Meta: d.IS{
			"source":    source,
			"structure": "single-data",
			"status":    "submited",
		},
		Data: data.ToResponse(),
	}, nil

}

func Complete(input e.ReadDetailDto) (*d.Data, error) {
	var data *e.McuOrder
	var err error

	event := pl.Event{
		Feature: "Complete",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "complete")

	err = dg.I.Transaction(func(tx *gorm.DB) error {
		data, err = ReadDetailData(input, &event, tx)
		if err != nil {
			return err
		}

		if data.IsCompleted() {
			return errors.New("data already completed")
		}

		data.Status_Code = erc.DSCDone
		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
	})

	if err != nil {
		return nil, err
	}

	return &d.Data{
		Meta: d.IS{
			"source":    source,
			"structure": "single-data",
			"status":    "fetched",
		},
		Data: data.ToResponse(),
	}, nil
}

func SetSchedule(input e.SetScheduleDto) (*d.Data, error) {
	rdDto := e.ReadDetailDto{Id: input.Id}
	var data *e.McuOrder
	var err error

	event := pl.Event{
		Feature: "SetSchedule",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "setSchedule")

	err = dg.I.Transaction(func(tx *gorm.DB) error {
		pl.SetLogInfo(&event, rdDto, "started", "DBReadDetail")
		data, err = ReadDetailData(rdDto, &event, tx)
		if err != nil {
			return err
		}
		if data.IsCompleted() {
			return errors.New("data already completed")
		}

		data.ExaminationDate = input.ExaminationDate
		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
	})

	if err != nil {
		return nil, err
	}

	return &d.Data{
		Meta: d.IS{
			"source":    source,
			"structure": "single-data",
			"status":    "setSchedule",
		},
		Data: data.ToResponse(),
	}, nil
}
