package installation

import (
	erc "simrs-vx/internal/domain/references/common"
	"strconv"

	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"

	e "simrs-vx/internal/domain/main-entities/installation"
	esync "simrs-vx/internal/domain/sync-entities/log"
)

const source = "installation"

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

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

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

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

		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err := mwRunner.RunCreateMiddleware(createPreMw, &input); err != nil {
			return err
		}

		return nil
	})

	if err = runLogMiddleware(err, input, 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.Installation
	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.Installation
	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{Code: input.Code}
	var data *e.Installation
	var err error

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

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

	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
		}

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

		mwRunner.setMwType(pu.MWTPre)
		// Run pre-middleware
		if err := mwRunner.RunUpdateMiddleware(updatePreMw, &input); err != nil {
			return err
		}

		return nil
	})

	if err = runLogMiddleware(err, input, 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{Code: input.Code}
	var data *e.Installation
	var err error

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

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

	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
		}

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

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

		return nil
	})

	if err = runLogMiddleware(err, input, 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, mwRunner *middlewareRunner) error {
	var errMsg string
	inputLog := esync.SimxLogDto{
		Payload: input,
		Method:  erc.CCCreate,
	}

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

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

	// create log success
	inputLog.IsSuccess = true
	if err = mwRunner.RunCreateLogMiddleware(createSimxLogMw, &inputLog); err != nil {
		return err
	}

	return nil
}
