package vehiclehist

import (
	"errors"
	vh "simrs-vx/internal/domain/main-entities/vehicle-hist"
	pu "simrs-vx/pkg/use-case-helper"

	plh "simrs-vx/pkg/lib-helper"
	pl "simrs-vx/pkg/logger"

	dg "github.com/karincake/apem/db-gorm-pg"
	gh "github.com/karincake/getuk"
	"gorm.io/gorm"
)

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

	data := vh.VehicleHist{}
	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 vh.ReadListDto, event *pl.Event, dbx ...*gorm.DB) ([]vh.VehicleHist, *vh.MetaDto, error) {
	pl.SetLogInfo(event, input, "started", "DBReadList")
	data := []vh.VehicleHist{}
	pagination := gh.Pagination{}
	count := int64(0)
	meta := vh.MetaDto{}

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

	tx = tx.
		Model(&vh.VehicleHist{}).
		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 errors.Is(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 vh.ReadDetailDto, event *pl.Event, dbx ...*gorm.DB) (*vh.VehicleHist, error) {
	pl.SetLogInfo(event, input, "started", "DBReadDetail")
	data := vh.VehicleHist{}

	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
}
