/*
Full-text index for Production Product Costing item lookup.
Target: SQL Server / URETIM.dbo.tbStok
*/

IF SERVERPROPERTY('IsFullTextInstalled') <> 1
BEGIN
  RAISERROR('SQL Server Full-Text Search yüklü değil.', 16, 1);
  RETURN;
END;
GO

IF DATABASEPROPERTYEX(DB_NAME(), 'IsFullTextEnabled') <> 1
BEGIN
  RAISERROR('Veritabanında Full-Text Search etkin değil.', 16, 1);
  RETURN;
END;
GO

IF OBJECT_ID('dbo.tbStok') IS NULL
BEGIN
  RAISERROR('dbo.tbStok bulunamadı.', 16, 1);
  RETURN;
END;
GO

IF NOT EXISTS (
  SELECT 1
  FROM sys.fulltext_catalogs
  WHERE name = 'FTC_ProductionProductCosting'
)
BEGIN
  CREATE FULLTEXT CATALOG FTC_ProductionProductCosting;
END;
GO

IF EXISTS (
  SELECT 1
  FROM sys.fulltext_indexes
  WHERE object_id = OBJECT_ID('dbo.tbStok')
)
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM sys.fulltext_index_columns fic
    INNER JOIN sys.columns c
      ON c.object_id = fic.object_id
     AND c.column_id = fic.column_id
    WHERE fic.object_id = OBJECT_ID('dbo.tbStok')
      AND c.name = 'sAciklama'
  )
  BEGIN
    ALTER FULLTEXT INDEX ON dbo.tbStok
      ADD (sAciklama LANGUAGE 1055);

    ALTER FULLTEXT INDEX ON dbo.tbStok
      START FULL POPULATION;
  END;
END;
ELSE
BEGIN
  DECLARE @keyIndex sysname;
  DECLARE @sql nvarchar(max);

  SELECT TOP 1 @keyIndex = i.name
  FROM sys.indexes i
  WHERE i.object_id = OBJECT_ID('dbo.tbStok')
    AND i.is_unique = 1
    AND i.is_disabled = 0
    AND i.type IN (1, 2)
  ORDER BY
    CASE WHEN i.is_primary_key = 1 THEN 0 ELSE 1 END,
    i.index_id;

  IF @keyIndex IS NULL
  BEGIN
    RAISERROR('dbo.tbStok için uygun unique key index bulunamadı.', 16, 1);
    RETURN;
  END;

  SET @sql = N'
CREATE FULLTEXT INDEX ON dbo.tbStok
(
  sAciklama LANGUAGE 1055
)
KEY INDEX ' + QUOTENAME(@keyIndex) + N'
ON [FTC_ProductionProductCosting]
WITH CHANGE_TRACKING AUTO;';

  EXEC sp_executesql @sql;

  ALTER FULLTEXT INDEX ON dbo.tbStok
    START FULL POPULATION;
END;
GO
