package soapi

import (
	"errors"
	erc "simrs-vx/internal/domain/references/common"
	esync "simrs-vx/internal/domain/sync-entities/log"
	"strconv"

	e "simrs-vx/internal/domain/main-entities/soapi"

	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 = "soapi"

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

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

	// Start log
	pl.SetLogInfo(&event, input, "started", "create")
	mwRunner := newMiddlewareRunner(&event, input.Sync)

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

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

		// get detail for sync
		soapiData, err := ReadDetailData(e.ReadDetailDto{
			Id:       data.Id,
			Includes: "Encounter,Employee.User"}, &event, tx)
		if err != nil {
			return err
		}

		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err = mwRunner.ExecuteIfSyncOn(func() error {
			return mwRunner.RunCreateMiddleware(createPreMw, soapiData)
		}); err != nil {
			return err
		}

		return nil
	})

	if err = runLogMiddleware(err, input, erc.CCCreate, mwRunner); err != nil {
		return nil, err
	}

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

	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 dataList []e.Soapi
	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 {
		if dataList, metaList, err = ReadListData(input, &event, tx); 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.Soapi
	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 {
		if data, err = ReadDetailData(input, &event, tx); 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.Soapi
	var err error

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

	// Start log
	pl.SetLogInfo(&event, input, "started", "update")
	mwRunner := newMiddlewareRunner(&event, input.Sync)

	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 err := UpdateData(input, data, &event, tx); err != nil {
			return err
		}

		// get detail for sync
		soapiData, err := ReadDetailData(e.ReadDetailDto{
			Id:       data.Id,
			Includes: "Encounter,Employee"}, &event)
		if err != nil {
			return err
		}

		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err = mwRunner.ExecuteIfSyncOn(func() error {
			return mwRunner.RunUpdateMiddleware(updatePreMw, soapiData)
		}); err != nil {
			return err
		}

		return nil
	})

	if err = runLogMiddleware(err, input, erc.CCUpdate, mwRunner); err != nil {
		return nil, err
	}

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

	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.Soapi
	var err error

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

	// Start log
	pl.SetLogInfo(&event, input, "started", "delete")
	mwRunner := newMiddlewareRunner(&event, input.Sync)

	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 err := DeleteData(data, &event, tx); err != nil {
			return err
		}

		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err = mwRunner.ExecuteIfSyncOn(func() error {
			return mwRunner.RunDeleteMiddleware(deletePreMw, &input)
		}); err != nil {
			return err
		}

		return nil
	})

	if err = runLogMiddleware(err, input, erc.CCDelete, mwRunner); err != nil {
		return nil, err
	}

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

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

}

func runLogMiddleware(err error, input any, method erc.CrudCode, mwRunner *middlewareRunner) error {
	var errMsg string
	inputLog := esync.SimxLogDto{
		Payload: input,
		Method:  method,
	}

	if err != nil {
		// Run log-middleware
		errMsg = err.Error()
		inputLog.ErrMessage = &errMsg
		inputLog.IsSuccess = false

		// create log failed
		if errMiddleware := mwRunner.ExecuteIfSyncOn(func() error {
			return mwRunner.RunCreateLogMiddleware(createSimxLogMw, &inputLog)
		}); errMiddleware != nil {
			return errMiddleware
		}

		return err
	}

	// create log success
	inputLog.IsSuccess = true
	err = mwRunner.ExecuteIfSyncOn(func() error {
		return mwRunner.RunCreateLogMiddleware(createSimxLogMw, &inputLog)
	})

	if err != nil {
		return err
	}

	return nil
}
