package queries

import (
	"context"
	"database/sql"
	"strings"
)

// ListProductFirstGroupOptions returns distinct ProductAtt42Desc (UrunIlkGrubu) values from Nebim V3.
func ListProductFirstGroupOptions(ctx context.Context, mssqlDB *sql.DB, search string, limit int) (*sql.Rows, error) {
	search = strings.TrimSpace(search)
	if mssqlDB == nil {
		return nil, sql.ErrConnDone
	}
	if limit <= 0 || limit > 5000 {
		limit = 5000
	}

	sqlText := `
SELECT TOP (@p2)
  LTRIM(RTRIM(ISNULL(ProductAtt42Desc, ''))) AS urun_ilk_grubu
FROM ProductFilterWithDescription('TR')
WHERE IsBlocked = 0
  AND LTRIM(RTRIM(ISNULL(ProductAtt42Desc, ''))) <> ''
  AND (
    @p1 = ''
    OR LTRIM(RTRIM(ISNULL(ProductAtt42Desc, ''))) LIKE '%' + @p1 + '%'
  )
GROUP BY LTRIM(RTRIM(ISNULL(ProductAtt42Desc, '')))
ORDER BY LTRIM(RTRIM(ISNULL(ProductAtt42Desc, '')));
`

	return mssqlDB.QueryContext(ctx, sqlText, search, limit)
}
