package queries

import (
	"github.com/fiskerinc/cloud-services/pkg/common/actionlogger"
	"github.com/pkg/errors"
)

type ActionLogInterface interface {
	Insert(log actionlogger.ActionLog) (err error)
	Select(filter actionlogger.ActionLogFilter) (logs []actionlogger.ActionLog, err error)
}

type ActionLogDB struct {
	QueryBase
}

// Insert implements ActionLog.
func (al *ActionLogDB) Insert(log actionlogger.ActionLog) (err error) {
	_, err = al.insert(&log)
	if err != nil {
		errors.WithStack(err)
	}
	return
}

// Select implements ActionLog.
func (al *ActionLogDB) Select(filter actionlogger.ActionLogFilter) (logs []actionlogger.ActionLog, err error) {
	query := al.GetDBConn().Model(&logs)
	if len(filter.VINs) > 0 {
		query.WhereIn("vin IN (?)", filter.VINs)
	}

	if len(filter.Actions) > 0 {
		query.WhereIn("action IN (?)", filter.Actions)
	}

	if filter.TrackingID != nil {
		query.Where("tracking_id = ?", &filter.TrackingID)
	}

	err = query.Select()
	if err != nil {
		errors.WithStack(err)
	}
	return
}

var _ ActionLogInterface = &ActionLogDB{}
