package queries

import (
	"fmt"

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

type RatePlanInterface interface {
	Select(string) (*common.RatePlanTMobile, error)
}

type RatePlanTmobile struct {
	QueryBase
}

func (rpt *RatePlanTmobile) Select(country string) (*common.RatePlanTMobile, error) {
	ratePlan := []common.RatePlanTMobile{}
	query := rpt.CreateSelectQuery(country, &ratePlan)

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

	if len(ratePlan) == 1 {
		return &ratePlan[0], nil
	} else if len(ratePlan) == 0 {
		return nil, fmt.Errorf("no rate plan exists for country %s", country)
	} else {
		return nil, fmt.Errorf("multiple rate plans exist for country %s", country)
	}
}

func (rpt *RatePlanTmobile) CreateSelectQuery(country string, ratePlan *[]common.RatePlanTMobile) *orm.Query {
	return rpt.GetDBConn().
		Model(ratePlan).
		Where("country = ?", country)
}
