if not exists (select top 1 1 from sys.objects where name = 'Permission' and type = 'U')
begin
	create table Permission
	(
		PermissionId int identity(1, 1) constraint PK_Permission primary key,
		PermissionCode varchar(50) not null,
		PermissionName varchar(100) not null,
		PermissionDescription varchar(300) not null
	)
end

if not exists (select top 1 1 from sys.objects where name = 'PermissionHierarchy' and type = 'U')
begin
	create table PermissionHierarchy
	(
		ParentPermissionId int not null constraint FK_PermissionHierarchy_Permission_Parent foreign key references Permission(PermissionId),
		ChildPermissionId int not null constraint FK_PermissionHierarchy_Permission_Child foreign key references Permission(PermissionId)
		constraint PK_PermissionHierarchy primary key (ParentPermissionId, ChildPermissionId)
	)
end

if not exists (select top 1 1 from Permission)
begin
	insert into Permission(PermissionCode, PermissionName, PermissionDescription)
	values ('VIEW_DASHBOARD', 'View dashboard', 'The user with this permission can view the dashboard.'),
           ('MANAGE_USERS', 'Manage users', 'The user with this permission can assign permissions to users.'),
           ('MANAGE_SETTINGS', 'Manage settings', 'The user with this permission can manage the application settings.'),
           ('VIEW_MACHINES', 'View machines', 'The user with this permission can view machines. He cannot start or stop a machine.'),
           ('MANAGE_MACHINES', 'Manage machines', 'The user with this permission can add, edit or delete machines.'),
		   ('OPERATE_MACHINES', 'Operate machines', 'The user with this permission can operate machines. He can start or stop machines.'),
		   ('GUEST_ACCESS', 'Guest access', 'The user with this permission can view the application in a read-only mode and with all data anonymized.')
end

if not exists (select top 1 1 from PermissionHierarchy)
begin
	declare @view_machines_permission_id int,
			@manage_machines_permission_id int,
			@operate_machines_permission_id int,
			@guest_access_permission_id int

	select @view_machines_permission_id = PermissionId from Permission where PermissionCode = 'VIEW_MACHINES'
	select @manage_machines_permission_id = PermissionId from Permission where PermissionCode = 'MANAGE_MACHINES'
	select @operate_machines_permission_id = PermissionId from Permission where PermissionCode = 'OPERATE_MACHINES'
	select @guest_access_permission_id = PermissionId from Permission where PermissionCode = 'GUEST_ACCESS'

	insert into PermissionHierarchy (ParentPermissionId, ChildPermissionId)
	values (@manage_machines_permission_id, @view_machines_permission_id),
		   (@operate_machines_permission_id, @view_machines_permission_id),
		   (@guest_access_permission_id, @view_machines_permission_id)
end