package de.oaa.xxx.registration;

import java.net.URI;
import java.util.UUID;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import de.oaa.xxx.user.Registration;
import de.oaa.xxx.user.UserController;


@RestController
@RequestMapping("/activation")
public class ActivationController {

    private final RegistrationRepository registrationRepository;
    private final UserController userController;

    public ActivationController(RegistrationRepository registrationRepository, UserController userController) {
        this.registrationRepository = registrationRepository;
        this.userController = userController;
    }

    @GetMapping("/{uuid}")
    public ResponseEntity<Void> activate(@PathVariable String uuid) {
        RegistrationEntity registration = registrationRepository.findById(UUID.fromString(uuid)).orElse(null);
        if (registration != null && !Boolean.TRUE.equals(registration.getActivated())) {
            Registration reg = new Registration();
            reg.setEmail(registration.getEmail());
            reg.setName(registration.getName());
            reg.setPasswordHash(registration.getPassword());

            ResponseEntity<Void> response = userController.userAnlegen(reg);
            if (response.getStatusCode().is2xxSuccessful()) {
                registration.setActivated(Boolean.TRUE);
                registrationRepository.save(registration);
                String redirect = "/login.html?email=" + java.net.URLEncoder.encode(registration.getEmail(), java.nio.charset.StandardCharsets.UTF_8);
                return ResponseEntity.status(302).location(URI.create(redirect)).build();
            } else {
                return ResponseEntity.internalServerError().build();
            }
        } else {
            return ResponseEntity.noContent().build();
        }
    }   
}
