package de.hft.geotime.controllers;

import de.hft.geotime.entities.TimetrackUser;
import de.hft.geotime.entities.projections.UserAllEmbeddedProjection;
import de.hft.geotime.repositories.TimetrackUserRepository;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.rest.webmvc.BasePathAwareController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@BasePathAwareController
@ResponseBody
public class UserController {

    private final TimetrackUserRepository userRepository;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
    private final ProjectionFactory projectionFactory;

    public UserController(TimetrackUserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder, ProjectionFactory projectionFactory) {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.projectionFactory = projectionFactory;
    }

    @GetMapping("/whoami")
    public UserAllEmbeddedProjection getUsername(Authentication authentication) {
        TimetrackUser user = userRepository.findFirstByUsername(authentication.getName());
        if (user != null) {
            return projectionFactory.createProjection(UserAllEmbeddedProjection.class, user);
        } else {
            return null;
        }
    }

    @PostMapping("/sign-up")
    public ResponseEntity<String> signUp(@RequestBody HashMap<String, String> signUpData) {
        if (signUpData.get("username") == null
                || signUpData.get("password") == null
                || signUpData.get("firstname") == null
                || signUpData.get("lastname") == null) {
            return new ResponseEntity<>("Missing information", HttpStatus.BAD_REQUEST);
        }

        TimetrackUser newUser = new TimetrackUser();
        newUser.setFirstname(signUpData.get("firstname"));
        newUser.setLastname(signUpData.get("lastname"));
        newUser.setPassword(bCryptPasswordEncoder.encode(signUpData.get("password")));
        newUser.setUsername(signUpData.get("username"));

        TimetrackUser byUsername = userRepository.findFirstByUsername(newUser.getUsername());
        if (byUsername == null) {
            userRepository.save(newUser);
            return new ResponseEntity<>("Created", HttpStatus.CREATED);
        } else {
            return new ResponseEntity<>("Username already exists!", HttpStatus.CONFLICT);
        }
    }

}
