package com.ankurm.authdemo.mfa;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Profile("layered")
public class OtpController {

    // A private manager that only knows the OTP provider. It is not a bean, so it cannot
    // disturb the shared AuthenticationManager or the provider auto-wiring.
    private final AuthenticationManager otpManager;
    private final SecurityContextHolderStrategy strategy = SecurityContextHolder.getContextHolderStrategy();
    private final SecurityContextRepository repository = new HttpSessionSecurityContextRepository();

    public OtpController(OtpVerifier verifier) {
        this.otpManager = new ProviderManager(new OtpStepUpProvider(verifier));
    }

    @PostMapping("/mfa/otp")
    public ResponseEntity<String> verify(@RequestParam String code, Authentication current,
                                         HttpServletRequest request, HttpServletResponse response) {
        Authentication upgraded;
        try {
            upgraded = otpManager.authenticate(new OtpAuthenticationToken(current, code));
        } catch (AuthenticationException ex) {
            return ResponseEntity.status(401).body("second factor rejected");
        }

        SecurityContext context = strategy.createEmptyContext();
        context.setAuthentication(upgraded);
        strategy.setContext(context);
        repository.saveContext(context, request, response); // without this the upgrade dies with the request
        return ResponseEntity.ok("second factor accepted for " + upgraded.getName());
    }
}
