package queries

import (
	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/go-pg/pg/v10"
	"github.com/go-pg/pg/v10/orm"
)

type TagsInterface interface {
	QueryBaseInterface
	Update(c *common.Car) (orm.Result, error)
	UpdateDistinctTags(car *common.Car) (orm.Result, error)
}

func NewTags() TagsInterface {
	return &Tags{}
}

type Tags struct {
	QueryBase
}

func (t *Tags) Update(car *common.Car) (orm.Result, error) {
	return t.resultWithStack(t.GetDBConn().Model(car).
		Column("tags").
		Where("vin = ?", car.VIN).Update())
}

func (t *Tags) UpdateDistinctTags(car *common.Car) (orm.Result, error) {
	return t.resultWithStack(t.GetDBConn().Model(car).
		Where("vin = ?", car.VIN).
		Set("tags = array(SELECT DISTINCT unnest(tags || ?))", pg.Array(car.Tags)).
		Update())
}
