package queries

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

// ListProductFirstGroupCodeDescOptions returns distinct (ProductAtt42, ProductAtt42Desc) values from Nebim V3.
// ProductAtt42: first group code
// ProductAtt42Desc: first group description
func ListProductFirstGroupCodeDescOptions(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(ProductAtt42, '')))     AS group_code,
  LTRIM(RTRIM(ISNULL(ProductAtt42Desc, ''))) AS group_title
FROM ProductFilterWithDescription('TR')
WHERE IsBlocked = 0
  AND LTRIM(RTRIM(ISNULL(ProductAtt42, ''))) <> ''
  AND LTRIM(RTRIM(ISNULL(ProductAtt42Desc, ''))) <> ''
  AND (
    @p1 = ''
    OR LTRIM(RTRIM(ISNULL(ProductAtt42, ''))) LIKE '%' + @p1 + '%'
    OR LTRIM(RTRIM(ISNULL(ProductAtt42Desc, ''))) LIKE '%' + @p1 + '%'
  )
GROUP BY
  LTRIM(RTRIM(ISNULL(ProductAtt42, ''))),
  LTRIM(RTRIM(ISNULL(ProductAtt42Desc, '')))
ORDER BY
  LTRIM(RTRIM(ISNULL(ProductAtt42Desc, ''))),
  LTRIM(RTRIM(ISNULL(ProductAtt42, '')));
`

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