package handlers

import (
	"encoding/json"
	"time"

	"github.com/fiskerinc/cloud-services/services/attendant/controllers"
	"github.com/fiskerinc/cloud-services/services/attendant/services"

	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/pkg/errors"
)

func UploadDtc(id string, data []byte) error {
	// ID is a vin in this case
	logger.Debug().Msgf("Upload DTC for %s", id)
	var DTCEntry controllers.DTCEntry
	DTCEntry.VIN = id

	err := json.Unmarshal(data, &DTCEntry)
	if err != nil {
		return err
	}

	if err = validator.GetValidator().Struct(&DTCEntry); err != nil {
		return errors.WithMessage(err, "failed structure validation")
	}

	err = DTCEntry.ParseSnapshot()
	if err != nil {
		logger.Warn().Msg(err.Error())
		return err
	}
	client, err := services.GetMongoClient()
	if err != nil {
		logger.Warn().Str("id", id).Err(err).Send()
		return err
	}
	dtcs := mongo.NewCollection(client.Collection("dtcs"))
	DTCEntry.CreatedAt = time.Now()
	_, err = dtcs.InsertOne(DTCEntry)
	return err
}
