package queries

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

type SwVersionRxSwinInterface interface {
	SelectByVersion(version string, options *PageQueryOptions) ([]common.SwVersionRxSwin, error)
	SelectCountByVersion(version string) (int, error)
	Insert(swVersionRxSwin *common.SwVersionRxSwin) (orm.Result, error)
	Delete(model *common.SwVersionRxSwin) (orm.Result, error)
}

type SwVersionRxSwin struct {
	QueryBase
}

func (svrs *SwVersionRxSwin) SelectByVersion(version string, options *PageQueryOptions) ([]common.SwVersionRxSwin, error) {
	swVersionRxSwins := []common.SwVersionRxSwin{}
	query := svrs.GetDBConn().Model(&swVersionRxSwins).Where("version = ?", version)

	svrs.pageQuery(query, options)

	err := query.Select()

	return swVersionRxSwins, errors.WithStack(err)
}

func (svrs *SwVersionRxSwin) SelectCountByVersion(version string) (int, error) {
	query := svrs.GetDBConn().Model(&[]common.SwVersionRxSwin{}).Where("version = ?", version)

	return query.Count()
}

func (svrs *SwVersionRxSwin) Insert(swVersionRxSwin *common.SwVersionRxSwin) (orm.Result, error) {
	return svrs.insert(swVersionRxSwin)
}

func (svrs *SwVersionRxSwin) Delete(model *common.SwVersionRxSwin) (orm.Result, error) {
	var err error
	total := &ORMResults{}
	tx, err := svrs.GetDBConn().Begin()
	if err != nil {
		return total, err
	}
	defer func() {
		if err != nil {
			tx.Rollback()
		}
		tx.Close()
	}()

	result, err := tx.Model(model).WherePK().Delete()
	if err != nil {
		return total, err
	}
	total.AddResult(result)

	err = tx.Commit()
	if err != nil {
		return total, err
	}

	return total, nil
}
