package usecase_helpers

import (
	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
)

// PopulateECUsCurrentVersion adds CurrentVersion field in provided ecus list of
// a specific vehicle, defined by vin.
// Since the ecus amount doesn't change, we don't need returning ecus and
// caller can use the same variable he provided in the function.
func PopulateECUsCurrentVersion(cars queries.CarsInterface, vin string, ecus []*common.UpdateManifestECU) error {
	ids := make([]string, 0, len(ecus))
	for _, ecu := range ecus {
		ids = append(ids, ecu.ECU)
	}

	carECUs, err := cars.GetCarECUs(common.CarECUFilter{VIN: vin, ECUs: ids, Unique: true}, nil)
	if err != nil {
		return err
	}

	carECUsMap := make(map[string]string, len(carECUs))
	for _, ecu := range carECUs {
		carECUsMap[ecu.ECU] = ecu.Version
	}

	for index, ecu := range ecus {
		ecu.CurrentVersion = carECUsMap[ecu.ECU]
		ecus[index] = ecu
	}

	return nil
}
