package store

import (
	"context"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/auth"
	"github.com/jackc/pgx/v5"
)

type UserGroupPolicy struct {
	ID                    string
	GroupKey              string
	Name                  string
	RateLimitPolicy       map[string]any
	BillingDiscountPolicy map[string]any
}

func (s *Store) ResolveUserGroupPolicy(ctx context.Context, user *auth.User) (UserGroupPolicy, error) {
	userGroupID := ""
	if user != nil {
		userGroupID = user.UserGroupID
	}
	var item UserGroupPolicy
	var rateLimit []byte
	var billing []byte
	err := s.pool.QueryRow(ctx, `
SELECT id::text, group_key, name, rate_limit_policy, billing_discount_policy
FROM gateway_user_groups
WHERE status = 'active'
  AND (($1 <> '' AND id = NULLIF($1, '')::uuid) OR ($1 = '' AND group_key = 'default'))
ORDER BY CASE WHEN id::text = $1 THEN 0 ELSE 1 END, priority ASC
LIMIT 1`, userGroupID).Scan(&item.ID, &item.GroupKey, &item.Name, &rateLimit, &billing)
	if err != nil {
		if err == pgx.ErrNoRows {
			return UserGroupPolicy{}, nil
		}
		return UserGroupPolicy{}, err
	}
	item.RateLimitPolicy = decodeObject(rateLimit)
	item.BillingDiscountPolicy = decodeObject(billing)
	return item, nil
}
