package dbAccess

import (
	"context"

	"git.fjla.uk/owlboard/go-types/pkg/database"
	"git.fjla.uk/owlboard/timetable-mgr/helpers"
	"git.fjla.uk/owlboard/timetable-mgr/log"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const timetableCollection string = "timetable"
const databaseName string = "owlboard"

func PushVersionToDb() {
	version := database.Version{
		Target:    "mq-client",
		Component: "mq-client",
		Version:   helpers.Version,
	}
	versionSelector := database.VersionSelector{
		Target:    "mq-client",
		Component: "mq-client",
	}
	opts := options.Update().SetUpsert(true)
	coll := MongoClient.Database("owlboard").Collection("versions")
	_, err := coll.UpdateOne(context.TODO(), versionSelector, bson.M{"$set": version}, opts)
	if err != nil {
		log.Msg.Warn("Unable to push version to database: " + err.Error())
	} else {
		log.Msg.Debug("Version up to date in Database")
	}
}

func PutOneService(data database.Service) bool {
	coll := MongoClient.Database(databaseName).Collection(timetableCollection)
	_, err := coll.InsertOne(context.TODO(), data)
	if err != nil {
		log.Msg.Error("Unable to insert to database: " + err.Error())
		return false
	}
	return true
}

func DeleteOneService(data database.DeleteQuery) bool {
	coll := MongoClient.Database(databaseName).Collection(timetableCollection)
	var filter = bson.D{
		{Key: "trainUid", Value: data.TrainUid},
		{Key: "stpIndicator", Value: data.StpIndicator},
		{Key: "scheduleStartDate", Value: data.ScheduleStartDate},
	}
	_, err := coll.DeleteOne(context.TODO(), filter)
	if err != nil {
		log.Msg.Error("Unable to delete service: " + err.Error())
		return false
	}
	return true
}
