package vehicle

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

	"gorm.io/gorm"

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

	evh "simrs-vx/internal/domain/main-entities/vehicle-hist"
	uvh "simrs-vx/internal/use-case/main-use-case/vehicle-hist"

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

const source = "vehicle"

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

	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
		}

		// Validate request
		if err := validateRequest(input, &event); err != nil {
			return err
		}

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

		// Set data for vehicle hist
		vehicleHistData := evh.CreateDto{
			Crud_Code: rcm.CCCreate,
			Vehicle:   data,
		}

		// Insert Vehicle Hist
		if _, err := uvh.CreateData(vehicleHistData, &event, tx); err != nil {
			return err
		}

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

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

		// Set data for vehicle hist
		vehicleHistData := evh.CreateDto{
			Crud_Code: rcm.CCRead,
			Vehicle:   *data,
		}

		// Insert Vehicle Hist
		if _, err := uvh.CreateData(vehicleHistData, &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 v.UpdateDto) (*d.Data, error) {
	rdDto := v.ReadDetailDto{Id: uint16(input.Id)}
	var data *v.Vehicle
	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
		}

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

		// Validate request
		if err := validateRequest(input.CreateDto, &event); err != nil {
			return err
		}

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

		// Set data for vehicle hist
		vehicleHistData := evh.CreateDto{
			Crud_Code: rcm.CCUpdate,
			Vehicle:   *data,
		}

		// Insert Vehicle Hist
		if _, err := uvh.CreateData(vehicleHistData, &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 v.DeleteDto) (*d.Data, error) {
	rdDto := v.ReadDetailDto{Id: input.Id}
	var data *v.Vehicle
	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
		}

		// Set data for vehicle hist
		vehicleHistData := evh.CreateDto{
			Crud_Code: rcm.CCDelete,
			Vehicle:   *data,
		}

		// Insert Vehicle Hist
		if _, err := uvh.CreateData(vehicleHistData, &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

}
