package queries

import (
	"time"

	"github.com/fiskerinc/cloud-services/pkg/common"

	"github.com/go-pg/pg/v10/orm"
	"github.com/pkg/errors"
)

const versionsAtSQL = "SELECT version_source, version FROM public.car_version_logs WHERE id IN (SELECT MAX(id) as id FROM public.car_version_logs WHERE vin = ? AND created_at <= ? GROUP BY vin, version_source)"

type CarVersionsLogInterface interface {
	LogVersionChange(log *common.CarVersionLogs) (orm.Result, error)
	SelectByVIN(vin string, options *PageQueryOptions) ([]common.CarVersionLogs, int, error)
	GetCarVersions(vin string, timestamp time.Time) (map[string]string, error)
}

// CarVersionsLog query methods
type CarVersionsLog struct {
	QueryBase
}

func (c *CarVersionsLog) LogVersionChange(log *common.CarVersionLogs) (orm.Result, error) {
	return c.insert(log)
}

func (c *CarVersionsLog) SelectByVIN(vin string, options *PageQueryOptions) ([]common.CarVersionLogs, int, error) {
	var logs []common.CarVersionLogs
	query := c.GetDBConn().Model(&logs).Where("vin = ?", vin)
	query = c.pageQuery(query, options)
	total, err := query.SelectAndCount()

	return logs, total, errors.WithStack(err)
}

func (c *CarVersionsLog) GetCarVersions(vin string, timestamp time.Time) (map[string]string, error) {
	logs := []common.CarVersionLogs{}
	result := map[string]string{}

	_, err := c.GetDBConn().Query(&logs, versionsAtSQL, vin, timestamp)
	if err == nil {
		result = map[string]string{}
		for _, log := range logs {
			result[string(log.VersionSource)] = log.Version
		}
	}

	return result, errors.WithStack(err)
}
