package queries

const GetProductColorSizes = `
------------------------------------------------------------
-- 🧩 GetProductColorSizes
-- Kullanım:
--   @p1 = ProductCode
--   @p2 = ColorCode
--   @p3 = ColorCode2
-- Açıklama:
--   Renk veya ikinci renk boşsa buna göre filtre uygular.
--   Renksiz (aksesuar) ürünlerde ColorCode='' kayıtlarını getirir.
------------------------------------------------------------

DECLARE @ProductCode NVARCHAR(30) = @p1;
DECLARE @ColorCode   NVARCHAR(30) = @p2;
DECLARE @ColorCode2  NVARCHAR(30) = @p3;

-- 🔧 Normalize parametreler (boşlukları kırp ve düzelt)
SET @ColorCode  = LTRIM(RTRIM(ISNULL(@ColorCode, '')));
SET @ColorCode2 = LTRIM(RTRIM(ISNULL(@ColorCode2, '')));

IF @ColorCode = ''
BEGIN
    SET @ColorCode = '';  -- tamamen renksiz ürün
END

IF @ColorCode2 = ''
BEGIN
    SET @ColorCode2 = NULL;  -- 2. renk yok
END

------------------------------------------------------------
-- 🔹 Ana sorgu
------------------------------------------------------------
SELECT 
    Product.ProductCode,
    ISNULL(prItemVariant.ColorCode, '')     AS ColorCode,
    ISNULL(prItemVariant.ItemDim1Code, '')  AS ItemDim1Code,
    ISNULL(prItemVariant.ItemDim2Code, '')  AS ItemDim2Code
FROM ProductFilterWithDescription('TR') AS Product
INNER JOIN cdItem
    ON cdItem.ItemTypeCode = 1
    AND cdItem.ItemCode = Product.ProductCode
LEFT JOIN prProductLot
    ON prProductLot.ItemTypeCode = cdItem.ItemTypeCode
    AND prProductLot.ItemCode = cdItem.ItemCode
    AND prProductLot.IsDefault = 1
LEFT JOIN prItemVariant
    ON prItemVariant.ItemCode = Product.ProductCode
WHERE 
    ProductAtt42 IN ('SERI','AKSESUAR')
    AND Product.IsBlocked = 0
    AND Product.ProductCode = @ProductCode
    AND (
        -- 🔸 1. renk doluysa o renk
        (LTRIM(RTRIM(@ColorCode)) <> '' AND prItemVariant.ColorCode = @ColorCode)
        -- 🔸 1. renk boşsa renksiz varyantlar
        OR (LTRIM(RTRIM(@ColorCode)) = '' AND (prItemVariant.ColorCode IS NULL OR LTRIM(RTRIM(prItemVariant.ColorCode)) = ''))
        -- 🔸 2. renk varsa ek olarak dahil et
        OR (@ColorCode2 IS NOT NULL AND prItemVariant.ColorCode = @ColorCode2)
    )
ORDER BY 
    prItemVariant.ItemDim1Code, 
    prItemVariant.ItemDim2Code;
`
