package com.sn.sowsysrestapi.api.controller;

import com.sn.sowsysrestapi.domain.exception.InvalidCredentialsException;
import com.sn.sowsysrestapi.domain.security.CredentialsDTO;
import com.sn.sowsysrestapi.domain.security.dao.UserDao;
import com.sn.sowsysrestapi.domain.security.jwt.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
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 org.springframework.web.server.ResponseStatusException;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/auth")
public class AuthenticationController {

    private final AuthenticationManager authenticationManager;
    private final UserDao userDao;
    private final JwtUtils jwtUtils;

    @PostMapping("/authenticate")
    public ResponseEntity<String> authenticate(@RequestBody CredentialsDTO credentials) {

        try {
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword())
            );

            final UserDetails user = userDao.findUserByUsername(credentials.getUsername());

            if (user != null) {
                return ResponseEntity.ok(jwtUtils.generateToken(user));
            }

            return ResponseEntity.status(400).body("Some error has ocurrered.");

        } catch (BadCredentialsException e) {
            throw new InvalidCredentialsException();
        }

    }

}
