package queries

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

// GetProductFirstGroupCodeDescByUrunKodu resolves (ProductAtt42, ProductAtt42Desc) for a given product code.
func GetProductFirstGroupCodeDescByUrunKodu(ctx context.Context, mssqlDB *sql.DB, urunKodu string) (code string, title string, err error) {
	urunKodu = strings.TrimSpace(urunKodu)
	if mssqlDB == nil || urunKodu == "" {
		return "", "", nil
	}

	sqlText := `
SELECT TOP 1
  LTRIM(RTRIM(ISNULL(ProductAtt42, '')))     AS group_code,
  LTRIM(RTRIM(ISNULL(ProductAtt42Desc, ''))) AS group_title
FROM ProductFilterWithDescription('TR')
WHERE IsBlocked = 0
  AND LTRIM(RTRIM(ProductCode)) = @p1
ORDER BY ProductCode;
`
	row := mssqlDB.QueryRowContext(ctx, sqlText, urunKodu)
	if err := row.Scan(&code, &title); err != nil {
		if err == sql.ErrNoRows {
			return "", "", nil
		}
		return "", "", err
	}
	return strings.TrimSpace(code), strings.TrimSpace(title), nil
}
