package queries

import (
	"database/sql"
	"strconv"
	"strings"

	"bssapp-backend/models"
)

// ========================================================
// 📌 GetOrderProductionItems — OrderHeaderID için U ürünleri
// ========================================================
func GetOrderProductionItems(mssql *sql.DB, orderHeaderID string) (*sql.Rows, error) {
	return mssql.Query(`
SELECT
    CAST(l.OrderHeaderID AS NVARCHAR(50)) AS OrderHeaderID,
    CAST(l.OrderLineID   AS NVARCHAR(50)) AS OrderLineID,
    l.ItemTypeCode       AS ItemTypeCode,
    ISNULL(l.ItemDim1Code,'') AS OldDim1,
    ISNULL(l.ItemDim3Code,'') AS OldDim3,

    ISNULL(l.ItemCode,'')      AS OldItemCode,
    ISNULL(l.ColorCode,'')     AS OldColor,
    ISNULL(l.ItemDim2Code,'')  AS OldDim2,
    ISNULL(l.LineDescription,'') AS OldDesc,

    CAST('' AS NVARCHAR(60))   AS NewItemCode,
    CAST('' AS NVARCHAR(30))   AS NewColor,
    CAST('' AS NVARCHAR(30))   AS NewDim2,
    CAST('' AS NVARCHAR(250))  AS NewDesc,

    CAST(0 AS bit) AS IsVariantMissing
FROM dbo.trOrderLine l
WHERE l.OrderHeaderID = @p1
  AND ISNULL(l.ItemCode,'') LIKE 'U%'
ORDER BY l.SortOrder, l.OrderLineID
`, orderHeaderID)
}

// ========================================================
// 📌 InsertMissingProductionVariants — eksik prItemVariant ekler
// ========================================================
func InsertMissingProductionVariants(mssql *sql.DB, orderHeaderID string, username string) (int64, error) {
	query := `
;WITH Missing AS (
    SELECT DISTINCT
        l.ItemTypeCode,
        l.ItemCode,
        l.ColorCode,
        l.ItemDim1Code,
        l.ItemDim2Code,
        l.ItemDim3Code
    FROM dbo.trOrderLine l
    LEFT JOIN dbo.prItemVariant pv
      ON pv.ItemTypeCode = l.ItemTypeCode
     AND pv.ItemCode     = l.ItemCode
     AND pv.ColorCode    = l.ColorCode
     AND ISNULL(pv.ItemDim1Code,'') = ISNULL(l.ItemDim1Code,'')
     AND ISNULL(pv.ItemDim2Code,'') = ISNULL(l.ItemDim2Code,'')
     AND ISNULL(pv.ItemDim3Code,'') = ISNULL(l.ItemDim3Code,'')
    WHERE l.OrderHeaderID = @p1
      AND ISNULL(l.ItemCode,'') LIKE 'U%'
      AND pv.ItemCode IS NULL
),
MaxPlu AS (
    SELECT ISNULL(MAX(PLU),0) AS BasePlu
    FROM dbo.prItemVariant WITH (UPDLOCK, HOLDLOCK)
)
INSERT INTO dbo.prItemVariant (
    ItemTypeCode,
    ItemCode,
    ColorCode,
    ItemDim1Code,
    ItemDim2Code,
    ItemDim3Code,
    PLU,
    IsSalesOrderClosed,
    IsPurchaseOrderClosed,
    IsLocked,
    IsBlocked,
    CreatedUserName,
    CreatedDate,
    LastUpdatedUserName,
    LastUpdatedDate,
    RowGuid,
    UseInternet,
    IsStoreOrderClosed
)
SELECT
    m.ItemTypeCode,
    m.ItemCode,
    m.ColorCode,
    m.ItemDim1Code,
    m.ItemDim2Code,
    m.ItemDim3Code,
    mp.BasePlu + ROW_NUMBER() OVER (ORDER BY m.ItemCode, m.ColorCode, m.ItemDim1Code, m.ItemDim2Code, m.ItemDim3Code),
    0,
    0,
    0,
    0,
    @p2,
    GETDATE(),
    @p2,
    GETDATE(),
    NEWID(),
    0,
    0
FROM Missing m
CROSS JOIN MaxPlu mp;
`

	res, err := mssql.Exec(query, orderHeaderID, username)
	if err != nil {
		return 0, err
	}
	return res.RowsAffected()
}

// ========================================================
// OrderProductionUpdate - variant kontrolu ve guncelleme
// ========================================================
func GetOrderLineDims(mssql *sql.DB, orderHeaderID string, orderLineID string) (int16, string, string, string, error) {
	var itemTypeCode int16
	var dim1 string
	var dim2 string
	var dim3 string
	err := mssql.QueryRow(`
SELECT
    ItemTypeCode,
    ISNULL(ItemDim1Code,'') AS ItemDim1Code,
    ISNULL(ItemDim2Code,'') AS ItemDim2Code,
    ISNULL(ItemDim3Code,'') AS ItemDim3Code
FROM dbo.trOrderLine
WHERE OrderHeaderID = @p1 AND OrderLineID = @p2
`, orderHeaderID, orderLineID).Scan(&itemTypeCode, &dim1, &dim2, &dim3)
	return itemTypeCode, dim1, dim2, dim3, err
}

func VariantExists(mssql *sql.DB, itemTypeCode int16, itemCode string, colorCode string, dim1 string, dim2 string, dim3 string) (bool, error) {
	var exists int
	err := mssql.QueryRow(`
SELECT TOP 1 1
FROM dbo.prItemVariant
WHERE ItemTypeCode = @p1
  AND ItemCode     = @p2
  AND ColorCode    = @p3
  AND ISNULL(ItemDim1Code,'') = ISNULL(@p4,'')
  AND ISNULL(ItemDim2Code,'') = ISNULL(@p5,'')
  AND ISNULL(ItemDim3Code,'') = ISNULL(@p6,'')
`, itemTypeCode, itemCode, colorCode, dim1, dim2, dim3).Scan(&exists)
	if err == sql.ErrNoRows {
		return false, nil
	}
	if err != nil {
		return false, err
	}
	return true, nil
}

func InsertMissingVariantsTx(
	tx *sql.Tx,
	missing []models.OrderProductionMissingVariant,
	username string,
	cdItemByCode map[string]models.OrderProductionCdItemDraft,
) (int64, error) {
	if len(missing) == 0 {
		return 0, nil
	}

	var basePlu int64
	if err := tx.QueryRow(`
SELECT ISNULL(MAX(PLU),0) AS BasePlu
FROM dbo.prItemVariant WITH (UPDLOCK, HOLDLOCK)
`).Scan(&basePlu); err != nil {
		return 0, err
	}

	var inserted int64
	ensuredItems := make(map[string]struct{}, len(missing))
	for i, v := range missing {
		itemKey := strconv.FormatInt(int64(v.ItemTypeCode), 10) + "|" + v.ItemCode
		if _, ok := ensuredItems[itemKey]; !ok {
			draft, hasDraft := cdItemByCode[itemKey]
			if !hasDraft {
				draft, hasDraft = cdItemByCode[NormalizeCdItemMapKey(v.ItemTypeCode, v.ItemCode)]
			}
			var draftPtr *models.OrderProductionCdItemDraft
			if hasDraft {
				tmp := draft
				draftPtr = &tmp
			}
			if err := ensureCdItemTx(tx, v.ItemTypeCode, v.ItemCode, username, draftPtr); err != nil {
				return inserted, err
			}
			ensuredItems[itemKey] = struct{}{}
		}

		plu := basePlu + int64(i) + 1
		res, err := tx.Exec(`
IF NOT EXISTS (
    SELECT 1
    FROM dbo.prItemVariant
    WHERE ItemTypeCode = @p1
      AND ItemCode     = @p2
      AND ColorCode    = @p3
      AND ISNULL(ItemDim1Code,'') = ISNULL(@p4,'')
      AND ISNULL(ItemDim2Code,'') = ISNULL(@p5,'')
      AND ISNULL(ItemDim3Code,'') = ISNULL(@p6,'')
)
INSERT INTO dbo.prItemVariant (
    ItemTypeCode,
    ItemCode,
    ColorCode,
    ItemDim1Code,
    ItemDim2Code,
    ItemDim3Code,
    PLU,
    IsSalesOrderClosed,
    IsPurchaseOrderClosed,
    IsLocked,
    IsBlocked,
    CreatedUserName,
    CreatedDate,
    LastUpdatedUserName,
    LastUpdatedDate,
    RowGuid,
    UseInternet,
    IsStoreOrderClosed
)
VALUES (
    @p1, @p2, @p3, @p4, @p5, @p6,
    @p7,
    0, 0, 0, 0,
    @p8, GETDATE(), @p8, GETDATE(),
    NEWID(),
    0,
    0
);
`, v.ItemTypeCode, v.ItemCode, v.ColorCode, v.ItemDim1Code, v.ItemDim2Code, v.ItemDim3Code, plu, username)
		if err != nil {
			return inserted, err
		}
		if rows, err := res.RowsAffected(); err == nil {
			inserted += rows
		}
	}
	return inserted, nil
}

func NormalizeCdItemMapKey(itemTypeCode int16, itemCode string) string {
	return strconv.FormatInt(int64(itemTypeCode), 10) + "|" + strings.ToUpper(strings.TrimSpace(itemCode))
}

func ensureCdItemTx(
	tx *sql.Tx,
	itemTypeCode int16,
	itemCode string,
	username string,
	draft *models.OrderProductionCdItemDraft,
) error {
	_, err := tx.Exec(`
IF NOT EXISTS (
	SELECT 1
	FROM dbo.cdItem
	WHERE ItemTypeCode = @p1
	  AND ItemCode = @p2
)
BEGIN
	;WITH Template AS (
		SELECT TOP 1
			ItemDimTypeCode, ProductTypeCode, ProductHierarchyID,
			UnitOfMeasureCode1, UnitOfMeasureCode2, UnitConvertRate, UnitConvertRateNotFixed,
			UseInternet, UsePOS, UseStore, EnablePartnerCompanies, UseManufacturing, UseSerialNumber,
			GenerateOpticalDataMatrixCode, ByWeight, SupplyPeriod, GuaranteePeriod, ShelfLife, OrderLeadTime,
			ItemAccountGrCode, ItemTaxGrCode, ItemPaymentPlanGrCode, ItemDiscountGrCode, ItemVendorGrCode,
			PromotionGroupCode, PromotionGroupCode2, ProductCollectionGrCode, StorePriceLevelCode, PerceptionOfFashionCode,
			CommercialRoleCode, StoreCapacityLevelCode, CustomsTariffNumberCode, IsFixedExpense, BOMEntityCode, CompanyCode,
			IsBlocked, IsLocked, LockedDate, IsSalesOrderClosed, IsPurchaseOrderClosed, UseRoll, UseBatch,
			MaxCreditCardInstallmentCount, GenerateSerialNumber, IsSubsequentDeliveryForR, IsSubsequentDeliveryForRI,
			IGACommissionGroup, UniFreeCommissionGroup, CustomsProductGroupCode, IsUTSDeclaratedItem, IsStoreOrderClosed
		FROM dbo.cdItem WITH (UPDLOCK, HOLDLOCK)
		WHERE ItemTypeCode = @p1
		  AND ItemCode LIKE 'U%'
		ORDER BY CreatedDate DESC
	)
	INSERT INTO dbo.cdItem (
		ItemTypeCode, ItemCode,
		ItemDimTypeCode, ProductTypeCode, ProductHierarchyID,
		UnitOfMeasureCode1, UnitOfMeasureCode2, UnitConvertRate, UnitConvertRateNotFixed,
		UseInternet, UsePOS, UseStore, EnablePartnerCompanies, UseManufacturing, UseSerialNumber,
		GenerateOpticalDataMatrixCode, ByWeight, SupplyPeriod, GuaranteePeriod, ShelfLife, OrderLeadTime,
		ItemAccountGrCode, ItemTaxGrCode, ItemPaymentPlanGrCode, ItemDiscountGrCode, ItemVendorGrCode,
		PromotionGroupCode, PromotionGroupCode2, ProductCollectionGrCode, StorePriceLevelCode, PerceptionOfFashionCode,
		CommercialRoleCode, StoreCapacityLevelCode, CustomsTariffNumberCode, IsFixedExpense, BOMEntityCode, CompanyCode,
		IsBlocked, IsLocked, LockedDate, IsSalesOrderClosed, IsPurchaseOrderClosed,
		CreatedUserName, CreatedDate, LastUpdatedUserName, LastUpdatedDate, RowGuid,
		UseRoll, UseBatch, MaxCreditCardInstallmentCount, GenerateSerialNumber,
		IsSubsequentDeliveryForR, IsSubsequentDeliveryForRI,
		IGACommissionGroup, UniFreeCommissionGroup, CustomsProductGroupCode, IsUTSDeclaratedItem, IsStoreOrderClosed
	)
	SELECT
		@p1, @p2,
		t.ItemDimTypeCode, t.ProductTypeCode, t.ProductHierarchyID,
		t.UnitOfMeasureCode1, t.UnitOfMeasureCode2, t.UnitConvertRate, t.UnitConvertRateNotFixed,
		t.UseInternet, t.UsePOS, t.UseStore, t.EnablePartnerCompanies, t.UseManufacturing, t.UseSerialNumber,
		t.GenerateOpticalDataMatrixCode, t.ByWeight, t.SupplyPeriod, t.GuaranteePeriod, t.ShelfLife, t.OrderLeadTime,
		t.ItemAccountGrCode, t.ItemTaxGrCode, t.ItemPaymentPlanGrCode, t.ItemDiscountGrCode, t.ItemVendorGrCode,
		t.PromotionGroupCode, t.PromotionGroupCode2, t.ProductCollectionGrCode, t.StorePriceLevelCode, t.PerceptionOfFashionCode,
		t.CommercialRoleCode, t.StoreCapacityLevelCode, t.CustomsTariffNumberCode, t.IsFixedExpense, t.BOMEntityCode, t.CompanyCode,
		t.IsBlocked, t.IsLocked, t.LockedDate, t.IsSalesOrderClosed, t.IsPurchaseOrderClosed,
		@p3, GETDATE(), @p3, GETDATE(), NEWID(),
		t.UseRoll, t.UseBatch, t.MaxCreditCardInstallmentCount, t.GenerateSerialNumber,
		t.IsSubsequentDeliveryForR, t.IsSubsequentDeliveryForRI,
		t.IGACommissionGroup, t.UniFreeCommissionGroup, t.CustomsProductGroupCode, t.IsUTSDeclaratedItem, t.IsStoreOrderClosed
	FROM Template t;

	IF @@ROWCOUNT = 0
	BEGIN
		INSERT INTO dbo.cdItem (
			ItemTypeCode, ItemCode,
			ItemDimTypeCode, ProductTypeCode, ProductHierarchyID,
			UnitOfMeasureCode1, UnitOfMeasureCode2, UnitConvertRate, UnitConvertRateNotFixed,
			UseInternet, UsePOS, UseStore, EnablePartnerCompanies, UseManufacturing, UseSerialNumber,
			GenerateOpticalDataMatrixCode, ByWeight, SupplyPeriod, GuaranteePeriod, ShelfLife, OrderLeadTime,
			ItemAccountGrCode, ItemTaxGrCode, ItemPaymentPlanGrCode, ItemDiscountGrCode, ItemVendorGrCode,
			PromotionGroupCode, PromotionGroupCode2, ProductCollectionGrCode, StorePriceLevelCode, PerceptionOfFashionCode,
			CommercialRoleCode, StoreCapacityLevelCode, CustomsTariffNumberCode, IsFixedExpense, BOMEntityCode, CompanyCode,
			IsBlocked, IsLocked, LockedDate, IsSalesOrderClosed, IsPurchaseOrderClosed,
			CreatedUserName, CreatedDate, LastUpdatedUserName, LastUpdatedDate, RowGuid,
			UseRoll, UseBatch, MaxCreditCardInstallmentCount, GenerateSerialNumber,
			IsSubsequentDeliveryForR, IsSubsequentDeliveryForRI,
			IGACommissionGroup, UniFreeCommissionGroup, CustomsProductGroupCode, IsUTSDeclaratedItem, IsStoreOrderClosed
		)
		VALUES (
			@p1, @p2,
			2, 1, 2,
			'AD', '', 0, 0,
			1, 1, 1, 0, 1, 0,
			0, 0, 0, 0, 0, 0,
			'', '10%', '', '', '',
			'', '', '0', '0', '0',
			'0', '', '', 0, '', '1',
			0, 0, '1900-01-01', 0, 0,
			@p3, GETDATE(), @p3, GETDATE(), NEWID(),
			0, 0, 12, 0,
			0, 0,
			'', '', '0', 0, 0
		);
	END
END
`, itemTypeCode, itemCode, username)
	if err != nil {
		return err
	}

	if draft == nil {
		return nil
	}

	_, err = tx.Exec(`
UPDATE dbo.cdItem
SET
	ItemDimTypeCode = COALESCE(@p3, ItemDimTypeCode),
	ProductTypeCode = COALESCE(@p4, ProductTypeCode),
	ProductHierarchyID = COALESCE(@p5, ProductHierarchyID),
	UnitOfMeasureCode1 = COALESCE(NULLIF(@p6,''), UnitOfMeasureCode1),
	ItemAccountGrCode = COALESCE(NULLIF(@p7,''), ItemAccountGrCode),
	ItemTaxGrCode = COALESCE(NULLIF(@p8,''), ItemTaxGrCode),
	ItemPaymentPlanGrCode = COALESCE(NULLIF(@p9,''), ItemPaymentPlanGrCode),
	ItemDiscountGrCode = COALESCE(NULLIF(@p10,''), ItemDiscountGrCode),
	ItemVendorGrCode = COALESCE(NULLIF(@p11,''), ItemVendorGrCode),
	PromotionGroupCode = COALESCE(NULLIF(@p12,''), PromotionGroupCode),
	ProductCollectionGrCode = COALESCE(NULLIF(@p13,''), ProductCollectionGrCode),
	StorePriceLevelCode = COALESCE(NULLIF(@p14,''), StorePriceLevelCode),
	PerceptionOfFashionCode = COALESCE(NULLIF(@p15,''), PerceptionOfFashionCode),
	CommercialRoleCode = COALESCE(NULLIF(@p16,''), CommercialRoleCode),
	StoreCapacityLevelCode = COALESCE(NULLIF(@p17,''), StoreCapacityLevelCode),
	CustomsTariffNumberCode = COALESCE(NULLIF(@p18,''), CustomsTariffNumberCode),
	CompanyCode = COALESCE(NULLIF(@p19,''), CompanyCode),
	LastUpdatedUserName = @p20,
	LastUpdatedDate = GETDATE()
WHERE ItemTypeCode = @p1
  AND ItemCode = @p2;
`,
		itemTypeCode,
		itemCode,
		draft.ItemDimTypeCode,
		draft.ProductTypeCode,
		draft.ProductHierarchyID,
		draft.UnitOfMeasureCode1,
		draft.ItemAccountGrCode,
		draft.ItemTaxGrCode,
		draft.ItemPaymentPlanGrCode,
		draft.ItemDiscountGrCode,
		draft.ItemVendorGrCode,
		draft.PromotionGroupCode,
		draft.ProductCollectionGrCode,
		draft.StorePriceLevelCode,
		draft.PerceptionOfFashionCode,
		draft.CommercialRoleCode,
		draft.StoreCapacityLevelCode,
		draft.CustomsTariffNumberCode,
		draft.CompanyCode,
		username,
	)
	return err
}

func UpdateOrderLinesTx(tx *sql.Tx, orderHeaderID string, lines []models.OrderProductionUpdateLine, username string) (int64, error) {
	var updated int64
	for _, line := range lines {
		res, err := tx.Exec(`
UPDATE dbo.trOrderLine
SET
    ItemCode = @p1,
    ColorCode = @p2,
    ItemDim2Code = @p3,
    LineDescription = COALESCE(NULLIF(@p4,''), LineDescription),
    LastUpdatedUserName = @p5,
    LastUpdatedDate = GETDATE()
WHERE OrderHeaderID = @p6 AND OrderLineID = @p7
`, line.NewItemCode, line.NewColor, line.NewDim2, line.NewDesc, username, orderHeaderID, line.OrderLineID)
		if err != nil {
			return updated, err
		}
		if rows, err := res.RowsAffected(); err == nil {
			updated += rows
		}
	}
	return updated, nil
}

func UpsertItemAttributesTx(tx *sql.Tx, attrs []models.OrderProductionItemAttributeRow, username string) (int64, error) {
	if len(attrs) == 0 {
		return 0, nil
	}

	var affected int64
	for _, a := range attrs {
		res, err := tx.Exec(`
IF EXISTS (
	SELECT 1
	FROM dbo.prItemAttribute
	WHERE ItemTypeCode = @p1
	  AND ItemCode = @p2
	  AND AttributeTypeCode = @p3
)
BEGIN
	UPDATE dbo.prItemAttribute
	SET
		AttributeCode = @p4,
		LastUpdatedUserName = @p5,
		LastUpdatedDate = GETDATE()
	WHERE ItemTypeCode = @p1
	  AND ItemCode = @p2
	  AND AttributeTypeCode = @p3
END
ELSE
BEGIN
	INSERT INTO dbo.prItemAttribute (
		ItemTypeCode,
		ItemCode,
		AttributeTypeCode,
		AttributeCode,
		CreatedUserName,
		CreatedDate,
		LastUpdatedUserName,
		LastUpdatedDate,
		RowGuid
	)
	VALUES (
		@p1,
		@p2,
		@p3,
		@p4,
		@p5,
		GETDATE(),
		@p5,
		GETDATE(),
		NEWID()
	)
END
`, a.ItemTypeCode, a.ItemCode, a.AttributeTypeCode, a.AttributeCode, username)
		if err != nil {
			return affected, err
		}
		if rows, err := res.RowsAffected(); err == nil {
			affected += rows
		}
	}
	return affected, nil
}

func GetOrderProductionLookupOptions(mssql *sql.DB) (models.OrderProductionCdItemLookups, error) {
	out := models.OrderProductionCdItemLookups{}

	queryPairs := []struct {
		Query  string
		Target *[]models.OrderProductionLookupOption
	}{
		{`SELECT
			CAST(t.ItemDimTypeCode AS NVARCHAR(50)) AS Code,
			ISNULL(d.ItemDimTypeDescription, CAST(t.ItemDimTypeCode AS NVARCHAR(50))) AS [Description]
		  FROM dbo.bsItemDimType t WITH(NOLOCK)
		  LEFT JOIN dbo.bsItemDimTypeDesc d WITH(NOLOCK)
		    ON d.ItemDimTypeCode = t.ItemDimTypeCode
		   AND d.LangCode = 'TR'
		  WHERE ISNULL(t.IsBlocked, 0) = 0
		  ORDER BY t.ItemDimTypeCode`, &out.ItemDimTypeCodes},
		{`SELECT DISTINCT CAST(ProductTypeCode AS NVARCHAR(50)) AS Code, CAST(ProductTypeCode AS NVARCHAR(50)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ProductTypeCode IS NOT NULL ORDER BY Code`, &out.ProductTypeCodes},
		{`SELECT
			CAST(h.ProductHierarchyID AS NVARCHAR(50)) AS Code,
			LTRIM(RTRIM(
				CONCAT(
					CAST(ISNULL(h.ProductHierarchyLevelCode01, 0) AS NVARCHAR(50)),
					CASE
						WHEN ISNULL(d.ProductHierarchyLevelDescription, '') <> '' THEN CONCAT(' - ', d.ProductHierarchyLevelDescription)
						ELSE ''
					END
				)
			)) AS [Description]
		  FROM dbo.dfProductHierarchy h WITH(NOLOCK)
		  LEFT JOIN dbo.cdProductHierarchyLevelDesc d WITH(NOLOCK)
		    ON d.ProductHierarchyLevelCode = h.ProductHierarchyLevelCode01
		   AND d.LangCode = 'TR'
		  ORDER BY h.ProductHierarchyID`, &out.ProductHierarchyIDs},
		{`SELECT DISTINCT CAST(UnitOfMeasureCode1 AS NVARCHAR(50)) AS Code, CAST(UnitOfMeasureCode1 AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(UnitOfMeasureCode1,'') <> '' ORDER BY Code`, &out.UnitOfMeasureCode1List},
		{`SELECT DISTINCT CAST(ItemAccountGrCode AS NVARCHAR(50)) AS Code, CAST(ItemAccountGrCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(ItemAccountGrCode,'') <> '' ORDER BY Code`, &out.ItemAccountGrCodes},
		{`SELECT DISTINCT CAST(ItemTaxGrCode AS NVARCHAR(50)) AS Code, CAST(ItemTaxGrCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(ItemTaxGrCode,'') <> '' ORDER BY Code`, &out.ItemTaxGrCodes},
		{`SELECT DISTINCT CAST(ItemPaymentPlanGrCode AS NVARCHAR(50)) AS Code, CAST(ItemPaymentPlanGrCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(ItemPaymentPlanGrCode,'') <> '' ORDER BY Code`, &out.ItemPaymentPlanGrCodes},
		{`SELECT DISTINCT CAST(ItemDiscountGrCode AS NVARCHAR(50)) AS Code, CAST(ItemDiscountGrCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(ItemDiscountGrCode,'') <> '' ORDER BY Code`, &out.ItemDiscountGrCodes},
		{`SELECT DISTINCT CAST(ItemVendorGrCode AS NVARCHAR(50)) AS Code, CAST(ItemVendorGrCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(ItemVendorGrCode,'') <> '' ORDER BY Code`, &out.ItemVendorGrCodes},
		{`SELECT DISTINCT CAST(PromotionGroupCode AS NVARCHAR(50)) AS Code, CAST(PromotionGroupCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(PromotionGroupCode,'') <> '' ORDER BY Code`, &out.PromotionGroupCodes},
		{`SELECT DISTINCT CAST(ProductCollectionGrCode AS NVARCHAR(50)) AS Code, CAST(ProductCollectionGrCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(ProductCollectionGrCode,'') <> '' ORDER BY Code`, &out.ProductCollectionGrCodes},
		{`SELECT DISTINCT CAST(StorePriceLevelCode AS NVARCHAR(50)) AS Code, CAST(StorePriceLevelCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(StorePriceLevelCode,'') <> '' ORDER BY Code`, &out.StorePriceLevelCodes},
		{`SELECT DISTINCT CAST(PerceptionOfFashionCode AS NVARCHAR(50)) AS Code, CAST(PerceptionOfFashionCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(PerceptionOfFashionCode,'') <> '' ORDER BY Code`, &out.PerceptionOfFashionCodes},
		{`SELECT DISTINCT CAST(CommercialRoleCode AS NVARCHAR(50)) AS Code, CAST(CommercialRoleCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(CommercialRoleCode,'') <> '' ORDER BY Code`, &out.CommercialRoleCodes},
		{`SELECT DISTINCT CAST(StoreCapacityLevelCode AS NVARCHAR(50)) AS Code, CAST(StoreCapacityLevelCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(StoreCapacityLevelCode,'') <> '' ORDER BY Code`, &out.StoreCapacityLevelCodes},
		{`SELECT DISTINCT CAST(CustomsTariffNumberCode AS NVARCHAR(50)) AS Code, CAST(CustomsTariffNumberCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(CustomsTariffNumberCode,'') <> '' ORDER BY Code`, &out.CustomsTariffNumbers},
		{`SELECT DISTINCT CAST(CompanyCode AS NVARCHAR(50)) AS Code, CAST(CompanyCode AS NVARCHAR(200)) AS [Description] FROM dbo.cdItem WITH(NOLOCK) WHERE ISNULL(CompanyCode,'') <> '' ORDER BY Code`, &out.CompanyCodes},
	}

	for _, pair := range queryPairs {
		rows, err := mssql.Query(pair.Query)
		if err != nil {
			return out, err
		}

		list := make([]models.OrderProductionLookupOption, 0, 64)
		for rows.Next() {
			var item models.OrderProductionLookupOption
			if err := rows.Scan(&item.Code, &item.Description); err != nil {
				rows.Close()
				return out, err
			}
			item.Code = strings.TrimSpace(item.Code)
			item.Description = strings.TrimSpace(item.Description)
			list = append(list, item)
		}
		if err := rows.Err(); err != nil {
			rows.Close()
			return out, err
		}
		rows.Close()
		*pair.Target = list
	}

	return out, nil
}
