package queries

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

type SUMSVersionsInterface interface {
	SelectAll(options *PageQueryOptions) ([]common.SUMSVersion, error)
	SelectAllCount() (int, error)
	Insert(u *common.SUMSVersion) (orm.Result, error)
	Delete(u *common.SUMSVersion) (orm.Result, error)
	Select(string) (*common.SUMSVersion, error)
}

type SUMSVersions struct {
	QueryBase
}

func (umv *SUMSVersions) SelectAll(options *PageQueryOptions) ([]common.SUMSVersion, error) {
	allUpdateManifestVersions := []common.SUMSVersion{}

	q := umv.GetDBConn().Model(&allUpdateManifestVersions)

	// Adding a limit to prevent unreasonably large queries
	// Expecting a paged query from the front end, so this should not be used
	if options != nil {
		umv.pageQuery(q, options)
	} else {
		umv.pageQuery(q, &PageQueryOptions{
			Limit: 500,
		})
	}

	err := q.Select()
	if err != nil {
		return nil, errors.WithStack(err)
	}

	return allUpdateManifestVersions, err
}

func (umv *SUMSVersions) SelectAllCount() (int, error) {
	allUpdateManifestVersions := []common.SUMSVersion{}

	return umv.GetDBConn().Model(&allUpdateManifestVersions).Count()
}

func (umv *SUMSVersions) Insert(u *common.SUMSVersion) (orm.Result, error) {
	return umv.insert(u)
}

func (umv *SUMSVersions) Delete(u *common.SUMSVersion) (orm.Result, error) {
	return umv.GetDBConn().Model(u).WherePK().Delete()
}

func (umv *SUMSVersions) Select(version string) (*common.SUMSVersion, error) {
	allUpdateManifestVersions := []common.SUMSVersion{}

	query := umv.GetDBConn().
		Model(&allUpdateManifestVersions).
		Where("version = ?", version).
		Order("os_version DESC")
	err := query.Select()

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

	if len(allUpdateManifestVersions) > 0 {
		return &allUpdateManifestVersions[0], nil
	} else {
		return nil, errors.New("empty result from database")
	}
}
