package net.savantly.sprout.starter.security.jwt;

import java.util.stream.Collectors;

import net.savantly.sprout.core.domain.user.SproutUser;
import net.savantly.sprout.core.domain.user.UserUpdateDto;
import net.savantly.sprout.core.security.SproutUserService;

public class DefaultJwtUserSynchronizer implements JwtUserSynchronizer {

	private final SproutUserService userService;

	public DefaultJwtUserSynchronizer(SproutUserService userService) {
		this.userService = userService;
	}

	@Override
	public void syncUser(SproutUser user) {
		userService.updateUser(new UserUpdateDto()
				.setFirstName(user.getFirstName())
				.setLastName(user.getLastName())
				.setRoles(user.getRoles().stream().map(r -> r.getName()).collect(Collectors.toList())));
	}

}

@@ -44,16 +44,39 @@
 y.jwt;%0A%0A
+import java.util.UUID;%0A
 import j
@@ -103,16 +103,16 @@
 ectors;%0A
-
 %0Aimport 
@@ -559,16 +559,73 @@
 user) %7B%0A
+%09%09if (userService.usernameExists(user.getUsername())) %7B%0A%09
 %09%09userSe
@@ -660,21 +660,48 @@
 ateDto()
-%0A%09%09%09%09
+.setUsername(user.getUsername())
 .setFirs
@@ -722,29 +722,24 @@
 FirstName())
-%0A%09%09%09%09
 .setLastName
@@ -759,16 +759,17 @@
 Name())%0A
+%09
 %09%09%09%09.set
@@ -853,14 +853,242 @@
 t())));%0A
+%09%09%7D else %7B%0A%09%09%09userService.createUser(user.getUsername(), UUID.randomUUID().toString(),%0A%09%09%09%09%09user.getPrimaryEmailAddress().getEmailAddress(),%0A%09%09%09%09%09user.getRoles().stream().map(r -%3E r.getName()).collect(Collectors.toList()));%0A%09%09%7D%0A
 %09%7D%0A%0A%7D%0A

add user if not exists