﻿-- Enable Service Broker
DECLARE @sql nvarchar(max)

SET @sql = N'ALTER DATABASE ' + DB_NAME() + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE '
EXEC master.sys.sp_executesql @sql

-- Ha a Service Broker IDja nem egyedi
IF EXISTS (SELECT 1 FROM sys.databases x WHERE x.service_broker_guid = (SELECT service_broker_guid FROM sys.databases d WHERE d.database_id = DB_ID()) AND x.database_id <> DB_ID()) BEGIN
  
  SET @sql = N'ALTER DATABASE ' + DB_NAME() + ' SET NEW_BROKER'
  EXEC master.sys.sp_executesql @sql
END
ELSE BEGIN
  SET @sql = N'ALTER DATABASE ' + DB_NAME() + ' SET ENABLE_BROKER'
  EXEC master.sys.sp_executesql @sql  
END

SET @sql = N'ALTER DATABASE ' + DB_NAME() + ' SET MULTI_USER'
EXEC master.sys.sp_executesql @sql
GO

-- Creating message
IF NOT EXISTS (SELECT 1 FROM sys.service_message_types WHERE name = 'AuditMessage') BEGIN
  CREATE MESSAGE TYPE AuditMessage 
    AUTHORIZATION kreta_tech_user
    --VALIDATION = WELL_FORMED_XML
END
GO


-- Creating contract
IF NOT EXISTS (SELECT 1 FROM sys.service_contracts WHERE name = 'AuditContract') BEGIN
  CREATE CONTRACT AuditContract
    AUTHORIZATION kreta_tech_user (AuditMessage SENT BY INITIATOR); 
END
GO

-- Creating queue
IF NOT EXISTS (SELECT 1 FROM sys.service_queues WHERE name = 'AuditQueue') BEGIN
  CREATE QUEUE auditlog.AuditQueue WITH STATUS=ON, ACTIVATION (
     STATUS = ON
    ,MAX_QUEUE_READERS = 1
    ,PROCEDURE_NAME = auditlog.usp_AuditProcessing
    ,EXECUTE AS 'kreta_tech_user'
  );
END
GO

-- Creating init Service 
IF NOT EXISTS (SELECT 1 FROM sys.services WHERE name = 'AuditServiceInit') BEGIN
  CREATE SERVICE AuditServiceInit
    AUTHORIZATION kreta_tech_user
    ON QUEUE auditlog.AuditQueue (AuditContract); 
END
GO

-- Creating target Service 
IF NOT EXISTS (SELECT 1 FROM sys.services WHERE name = 'AuditServiceTarget') BEGIN
  CREATE SERVICE AuditServiceTarget
    AUTHORIZATION kreta_tech_user 
    ON QUEUE auditlog.AuditQueue (AuditContract); 
END
GO
