/*
Product filter cache refresh for Product Stock By Attributes endpoints.
This cache is used by backend queries when dbo.ProductFilterTRCache exists.
*/

USE BAGGI_V3;
GO

IF OBJECT_ID('dbo.ProductFilterTRCache','U') IS NULL
BEGIN
  CREATE TABLE dbo.ProductFilterTRCache
  (
    ProductCode NVARCHAR(50) NOT NULL PRIMARY KEY,
    ProductDescription NVARCHAR(255) NULL,
    ProductAtt01Desc NVARCHAR(255) NULL,
    ProductAtt02Desc NVARCHAR(255) NULL,
    ProductAtt11Desc NVARCHAR(255) NULL,
    ProductAtt38Desc NVARCHAR(255) NULL,
    ProductAtt41Desc NVARCHAR(255) NULL,
    ProductAtt44Desc NVARCHAR(255) NULL
  );
END
GO

TRUNCATE TABLE dbo.ProductFilterTRCache;
GO

INSERT INTO dbo.ProductFilterTRCache
(
  ProductCode,
  ProductDescription,
  ProductAtt01Desc,
  ProductAtt02Desc,
  ProductAtt11Desc,
  ProductAtt38Desc,
  ProductAtt41Desc,
  ProductAtt44Desc
)
SELECT
  ProductCode,
  ProductDescription,
  ProductAtt01Desc,
  ProductAtt02Desc,
  ProductAtt11Desc,
  ProductAtt38Desc,
  ProductAtt41Desc,
  ProductAtt44Desc
FROM ProductFilterWithDescription('TR')
WHERE LEN(ProductCode) = 13;
GO

IF EXISTS (
  SELECT 1 FROM sys.indexes
  WHERE name = 'IX_ProductFilterTRCache_Filter'
    AND object_id = OBJECT_ID('dbo.ProductFilterTRCache')
)
BEGIN
  DROP INDEX IX_ProductFilterTRCache_Filter ON dbo.ProductFilterTRCache;
END
GO

IF NOT EXISTS (
  SELECT 1 FROM sys.indexes
  WHERE name = 'IX_ProductFilterTRCache_KatAna'
    AND object_id = OBJECT_ID('dbo.ProductFilterTRCache')
)
BEGIN
  CREATE NONCLUSTERED INDEX IX_ProductFilterTRCache_KatAna
  ON dbo.ProductFilterTRCache (ProductAtt44Desc, ProductAtt01Desc, ProductCode)
  INCLUDE (ProductDescription, ProductAtt02Desc, ProductAtt41Desc, ProductAtt38Desc, ProductAtt11Desc);
END
GO

IF NOT EXISTS (
  SELECT 1 FROM sys.indexes
  WHERE name = 'IX_ProductFilterTRCache_KatAnaAlt'
    AND object_id = OBJECT_ID('dbo.ProductFilterTRCache')
)
BEGIN
  CREATE NONCLUSTERED INDEX IX_ProductFilterTRCache_KatAnaAlt
  ON dbo.ProductFilterTRCache (ProductAtt44Desc, ProductAtt01Desc, ProductAtt02Desc, ProductCode)
  INCLUDE (ProductDescription, ProductAtt41Desc, ProductAtt38Desc, ProductAtt11Desc);
END
GO

UPDATE STATISTICS dbo.ProductFilterTRCache WITH FULLSCAN;
GO
