package com.wishurgift.entry.security;

import com.wishurgift.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;
import java.security.Principal;

import static com.wishurgift.utils.Constant.AUTHENTICATION_SCHEME;

@Slf4j
@Connected
@Provider
@Priority(Priorities.AUTHENTICATION)
public class ConnectedAuthenticationFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) {
        log.info("Enter in ConnectedAuthenticationFilter");
        // Recupération du header
        String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validation du header
        if (!JwtUtils.isTokenAuthentication(authorizationHeader)) {
            log.info("Authorization header not found or invalid");
            return;
        }

        // Extraction du token
        String token = authorizationHeader.substring(AUTHENTICATION_SCHEME.length()).trim();

        // Verification du token
        if (!JwtUtils.verify(token)) {
            log.info("JWT authentication token is invalid");
            return;
        }
        log.info("User connected, token: {}", token.split("\\.")[1]);

        // Definition de contexte de securité
        final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
        requestContext.setSecurityContext(new SecurityContext() {

            @Override
            public Principal getUserPrincipal() {
                return () -> token;
            }

            @Override
            public boolean isUserInRole(String role) {
                return true;
            }

            @Override
            public boolean isSecure() {
                return currentSecurityContext.isSecure();
            }

            @Override
            public String getAuthenticationScheme() {
                return AUTHENTICATION_SCHEME;
            }
        });
    }


}
