package featurerepo

import (
	"git.ma-al.com/goc_daniel/b2b/app/db"
	"git.ma-al.com/goc_daniel/b2b/app/model/dbmodel"
)

type FeatureGroupWithValues struct {
	FeatureName string
	Values      map[uint]string
}

type UIFeatureRepo interface {
	GetFeaturesWithValues(featureIDs []uint, featureValueIDs []uint, idLang uint) (map[uint]FeatureGroupWithValues, error)
}

type FeatureRepo struct{}

func New() UIFeatureRepo {
	return &FeatureRepo{}
}

func (r *FeatureRepo) GetFeaturesWithValues(featureIDs []uint, featureValueIDs []uint, idLang uint) (map[uint]FeatureGroupWithValues, error) {
	result := make(map[uint]FeatureGroupWithValues)

	if len(featureIDs) == 0 && len(featureValueIDs) == 0 {
		return result, nil
	}

	if len(featureValueIDs) > 0 {
		type valueResult struct {
			IDFeatureValue int32
			IDFeature      int32
			Value          string
		}

		var values []valueResult
		if err := db.Get().
			Model(dbmodel.PsFeatureValueLang{}).
			Select(`
				ps_feature_value_lang.id_feature_value,
				ps_feature_value.id_feature,
				COALESCE(ps_feature_value_lang.value, '') as value
			`).
			Joins("LEFT JOIN ps_feature_value ON ps_feature_value.id_feature_value = ps_feature_value_lang.id_feature_value").
			Where("ps_feature_value_lang.id_lang = ?", idLang).
			Where("ps_feature_value_lang.id_feature_value IN ?", featureValueIDs).
			Scan(&values).Error; err != nil {
			return nil, err
		}

		for _, v := range values {
			if _, exists := result[uint(v.IDFeature)]; !exists {
				result[uint(v.IDFeature)] = FeatureGroupWithValues{
					FeatureName: v.Value,
					Values:      make(map[uint]string),
				}
			}
			result[uint(v.IDFeature)].Values[uint(v.IDFeatureValue)] = v.Value
		}
	}

	if len(featureIDs) > 0 {
		type featureResult struct {
			IDFeature   int32
			FeatureName string
		}

		var features []featureResult
		if err := db.Get().
			Model(dbmodel.PsFeatureLang{}).
			Select("ps_feature_lang.id_feature, COALESCE(ps_feature_lang.name, '') as feature_name").
			Where("ps_feature_lang.id_feature IN ?", featureIDs).
			Where("ps_feature_lang.id_lang = ?", idLang).
			Scan(&features).Error; err != nil {
			return nil, err
		}

		for _, f := range features {
			if existing, ok := result[uint(f.IDFeature)]; ok {
				if f.FeatureName != "" {
					existing.FeatureName = f.FeatureName
					result[uint(f.IDFeature)] = existing
				}
			} else {
				result[uint(f.IDFeature)] = FeatureGroupWithValues{
					FeatureName: f.FeatureName,
					Values:      make(map[uint]string),
				}
			}
		}
	}

	return result, nil
}
