package queries

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

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

type SubscriptionPackagesInterface interface {
	Delete(model *common.SubscriptionPackage) (orm.Result, error)
	Insert(model *common.SubscriptionPackage) (orm.Result, error)
	Update(model *common.SubscriptionPackage) (orm.Result, error)
	Count(filter *common.SubscriptionPackage) (int, error)
	Select(fitler *common.SubscriptionPackage, paging *PageQueryOptions) ([]common.SubscriptionPackage, error)
	Load(model *common.SubscriptionPackage) error
	AddFeature(pack *common.SubscriptionPackage, feature *common.SubscriptionFeature) (bool, error)
	AssociateFeature(packageid uuid.UUID, featureid uuid.UUID) (bool, error)
}

type SubscriptionPackages struct {
	QueryBase
}

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

	result, err := tx.Model(&common.SubscriptionPackageToFeature{SubscriptionPackageID: model.ID}).Where("subscription_package_id = ?subscription_package_id").Delete()
	if err != nil {
		return total, errors.WithStack(err)
	}
	total.AddResult(result)

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

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

	return total, nil
}

func (sp *SubscriptionPackages) Insert(model *common.SubscriptionPackage) (orm.Result, error) {
	return sp.insert(model)
}

func (sp *SubscriptionPackages) Update(model *common.SubscriptionPackage) (orm.Result, error) {
	return sp.update(model)
}

func (sp *SubscriptionPackages) Count(filter *common.SubscriptionPackage) (int, error) {
	query := sp.GetDBConn().Model(filter)

	sp.selectFilter(query, filter)

	count, err := query.Count()

	return count, errors.WithStack(err)
}

func (sp *SubscriptionPackages) selectFilter(query *orm.Query, filter *common.SubscriptionPackage) {
	if filter.ID != uuid.Nil {
		query.Where("id = ?", filter.ID)
	}

	if filter.Name != "" {
		query.Where("name = ?", filter.Name)
	}
}

func (sp *SubscriptionPackages) Select(filter *common.SubscriptionPackage, paging *PageQueryOptions) ([]common.SubscriptionPackage, error) {
	items := []common.SubscriptionPackage{}
	query := sp.GetDBConn().Model(&items)

	sp.selectFilter(query, filter)
	if paging != nil {
		sp.pageQuery(query, paging)
	}

	err := query.Select()

	return items, errors.WithStack(err)
}

func (sp *SubscriptionPackages) Load(model *common.SubscriptionPackage) error {
	var err error
	tx, err := sp.GetDBConn().Begin()
	if err != nil {
		return errors.WithStack(err)
	}
	defer func() {
		if err != nil {
			tx.Rollback()
		}
		tx.Close()
	}()

	err = tx.Model(model).WherePK().First()
	if err != nil {
		return errors.WithStack(err)
	}

	features := []common.SubscriptionFeature{}
	err = tx.Model(&features).Join("JOIN subscription_package_to_features").JoinOn("subscription_package_to_features.subscription_feature_id = subscription_feature.id").Where("subscription_package_to_features.subscription_package_id = ?", model.ID).Select()
	if err != nil {
		return errors.WithStack(err)
	}

	model.Features = features

	return nil
}

func (sp *SubscriptionPackages) AddFeature(model *common.SubscriptionPackage, feature *common.SubscriptionFeature) (bool, error) {
	result, err := sp.AssociateFeature(model.ID, feature.ID)
	if err == nil {
		model.AddFeature(feature)
	}

	return result, err
}

func (sp *SubscriptionPackages) AssociateFeature(packageid uuid.UUID, featureid uuid.UUID) (bool, error) {
	inserted, err := sp.GetDBConn().Model(&common.SubscriptionPackageToFeature{
		SubscriptionPackageID: packageid,
		SubscriptionFeatureID: featureid,
	}).SelectOrInsert()

	return inserted, errors.WithStack(err)
}

func (sp *SubscriptionPackages) RemoveFeature(model *common.SubscriptionPackage, feature *common.SubscriptionFeature) (orm.Result, error) {
	result, err := sp.resultWithStack(sp.GetDBConn().Model((*common.SubscriptionPackageToFeature)(nil)).Where("package_id = ? AND feature_id = ?", model.ID, feature.ID).Delete())
	if err == nil {
		model.RemoveFeature(feature)
	}

	return result, err
}
