﻿IF NOT EXISTS (SELECT 1 FROM sys.service_message_types WHERE name = 'AuditMessage') BEGIN
  CREATE MESSAGE TYPE [AuditMessage]
    VALIDATION = WELL_FORMED_XML;
END
GO

IF NOT EXISTS (SELECT 1 FROM sys.service_message_types WHERE name = 'EndOfStream') BEGIN
  CREATE MESSAGE TYPE EndOfStream;
END
GO

IF NOT EXISTS (SELECT 1 FROM sys.service_contracts WHERE name = 'AuditContract') BEGIN
  CREATE CONTRACT [AuditContract] (
    [AuditMessage] SENT BY INITIATOR,
    [EndOfStream] SENT BY INITIATOR
	);
END
GO

IF OBJECT_ID('auditlog.usp_AuditProcessing') IS NULL BEGIN
  EXEC('CREATE PROCEDURE auditlog.usp_AuditProcessing AS SELECT 1')
END

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

IF NOT EXISTS (SELECT 1 FROM sys.services WHERE name = 'AuditService') BEGIN
  CREATE SERVICE [AuditService]
    ON QUEUE auditlog.AuditQueue ([AuditContract]);
END
GO

