package za.co.rootbranch.coffeechat.controllers;

import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import za.co.rootbranch.coffeechat.models.APIResponse;
import za.co.rootbranch.coffeechat.models.User;
import za.co.rootbranch.coffeechat.repositories.UserRepository;
import za.co.rootbranch.coffeechat.security.JwtUtil;

@CrossOrigin("*")
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    UserRepository userRepository;
    @Autowired
    PasswordEncoder encoder;
    @Autowired
    JwtUtil jwtUtils;

    @PostMapping("/signin")
    public APIResponse authenticateUser(@RequestBody User user) {

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        user.getEmail(),
                        user.getPassword()
                // encoder.encode("Password") // user.getPassword()

                ));
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return new APIResponse("success", jwtUtils.GenerateToken(userDetails.getUsername()));
    }

    @PostMapping("/signup")
    public APIResponse registerUser(@RequestBody User user) {
        if (userRepository.existsByEmail(user.getEmail())) {
            return new APIResponse("Fail", "Error: Username is already taken!");
        }
        // Create new user's account
        User newUser = new User(
                null,
                user.getEmail(),
                user.getEmail(),
                encoder.encode(user.getPassword())

        // encoder.encode("Password")
        );
        // encoder.encode(user.getPassword()));
        userRepository.save(newUser);
        return new APIResponse("Success", "User registered successfully!");
    }
}
