if not exists (select top 1 1 from sys.objects where name = 'Bot' and type = 'U')
begin
	create table Bot
	(
		BotId uniqueidentifier constraint DF_Bot_BotId default newid() not null,
		BotCode varchar(100) not null,
		BotName varchar(255) not null,
		CreationDate datetime constraint DF_Bot_CreationDate default getdate(),
		constraint PK_Bot primary key (BotId)
	)
end
go

if not exists (select top 1 1 from sys.objects where name = 'BotSession' and type = 'U')
begin
	create table BotSession
	(
		SessionId uniqueidentifier constraint DF_BotSession_SessionId default newid() not null,
		StartDate datetime constraint DF_BotSession_StartDate default getdate(),
		BotId uniqueidentifier not null,
		ExternalId uniqueidentifier not null,
		ClientApplication varchar(100) not null,
		UserKey varchar(100) not null,
		constraint PK_BotSession primary key (SessionId),
		constraint FK_BotSession_Bot foreign key (BotId) references Bot(BotId)
	)
end
go

if not exists (select top 1 1 from sys.objects where name = 'Chat' and type = 'U')
begin
	create table Chat
	(
		ChatId uniqueidentifier constraint DF_Chat_ChatId default newid() not null,
		SessionId uniqueidentifier not null,
		StartDate datetime constraint DF_Chat_StartDate default getdate(),
		StopDate datetime,
		constraint PK_Chat primary key (ChatId),
		constraint FK_Chat_BotSession foreign key (ChatId) references BotSession(SessionId)
	)
end
go

if not exists (select top 1 1 from sys.objects where name = 'MessageSource' and type = 'U')
begin
	create table MessageSource
	(
		MessageSourceId int not null,
		MessageSourceCode varchar(20) not null,
		MessageSourceName varchar(100) not null,
		constraint PK_MessageSource primary key (MessageSourceId)
	)
end
go

if not exists (select top 1 1 from sys.objects where name = 'ChatMessage' and type = 'U')
begin
	create table ChatMessage
	(
		MessageId int identity(0, 1),
		ChatId uniqueidentifier not null,
		MessageSourceId int not null,
		MessageDate datetime constraint DF_ChatMessage_MessageDate default getdate(),
		MessageContent varchar(max)
		constraint PK_ChatMessage primary key (MessageId),
		constraint FK_ChatMessage_Chat foreign key (ChatId) references Chat(ChatId),
		constraint FK_ChatMessage_MessageSource foreign key (MessageSourceId) references MessageSource(MessageSourceId)
	)
end
go