package vehiclehist

import (
	"strconv"

	"gorm.io/gorm"

	vh "simrs-vx/internal/domain/main-entities/vehicle-hist"
	pl "simrs-vx/pkg/logger"
	pu "simrs-vx/pkg/use-case-helper"

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

const source = "vehicle-hist"

func ReadList(input vh.ReadListDto) (*d.Data, error) {
	var data *vh.VehicleHist
	var dataList []vh.VehicleHist
	var metaList *vh.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: vh.ToResponseList(dataList),
	}, nil
}

func ReadDetail(input vh.ReadDetailDto) (*d.Data, error) {
	var data *vh.VehicleHist
	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
}
