package it.powerbyte.springbootstarter.controller.auth;

import it.powerbyte.springbootstarter.entity.User;
import it.powerbyte.springbootstarter.models.AuthenticationRequest;
import it.powerbyte.springbootstarter.models.AuthenticationResponse;
import it.powerbyte.springbootstarter.models.RefreshTokenRequest;
import it.powerbyte.springbootstarter.models.UserInformation;
import it.powerbyte.springbootstarter.service.AuthService;
import it.powerbyte.springbootstarter.service.RefreshTokenService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Base64;
import java.util.Optional;

import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.HttpStatus.OK;

@RestController
@AllArgsConstructor
@CrossOrigin(maxAge = 3600, origins = "http://localhost:4200/login", allowCredentials="true")
public class AuthenticationController {

    private final AuthService authService;
    private final RefreshTokenService refreshTokenService;

    @PostMapping("/auth/login")
    private AuthenticationResponse login(@RequestBody AuthenticationRequest authenticationBean) {
        AuthenticationResponse response = authService.login(authenticationBean);
        return response;
    }

    @RequestMapping("/user")
    public Principal user(HttpServletRequest request) {
        String authToken = request.getHeader("Authorization")
                .substring("Basic".length()).trim();
        return () ->  new String(Base64.getDecoder()
                .decode(authToken)).split(":")[0];
    }

    @RequestMapping("/user/{username}")
    public ResponseEntity<UserInformation> user(@PathVariable("username") String username, HttpServletRequest request) {
        Optional<User> user = authService.getUserDetails(username);
        if (user.isPresent()) {
            UserInformation userInformation = new UserInformation(
                    user.get().getUsername(),
                    user.get().getRole(),
                    user.get().getFirstname(),
                    user.get().getLastname(),
                    user.get().getEmail(),
                    user.get().getLastLogin()
            );

            return ResponseEntity
                .status(OK)
                .body(userInformation);
        } else {
            return ResponseEntity
                    .status(NOT_FOUND)
                    .body(null)
                    ;
        }


    }

    @PostMapping("/refresh/token")
    public AuthenticationResponse refreshTokens(@Valid @RequestBody RefreshTokenRequest refreshTokenRequest) {
        return authService.refreshToken(refreshTokenRequest);
    }

    @PostMapping("/logout")
    public ResponseEntity<String> logout(@Valid @RequestBody RefreshTokenRequest refreshTokenRequest) {
        refreshTokenService.deleteRefreshToken(refreshTokenRequest.getRefreshToken());
        return ResponseEntity.status(OK).body("Refresh Token Deleted Successfully!!");
    }
}
