package cz.muni.fi.pa165.core.Jwt;

import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.Payload;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.text.ParseException;
import java.util.Map;

@Service
public class JwtFilter extends OncePerRequestFilter {
    private final JwtUserDetailsService jwtUserDetailsService;

    public JwtFilter(JwtUserDetailsService jwtUserDetailsService) {
        this.jwtUserDetailsService = jwtUserDetailsService;
    }

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getRequestURI().equals("/api/user") && request.getMethod().equals("POST")) {
            filterChain.doFilter(request, response);
            return;
        }

        String headerValue = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.hasText(headerValue) && headerValue.startsWith("Bearer ")) {
            String token = headerValue.substring(7);

            JWSObject jwsObject = null;
            try {
                jwsObject = JWSObject.parse(token);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            Payload payload = jwsObject.getPayload();
            Map<String, Object> jsonObject = payload.toJSONObject();

            String email = (String) jsonObject.get("email");

            JwtUser user = (JwtUser) jwtUserDetailsService.loadUserByUsername(email);

            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()));

            filterChain.doFilter(request, response);
        }

        throw new Exception("Unauthorized");
    }
}