package de.avatic.lcc.config.filter;
import de.avatic.lcc.service.apps.JwtTokenService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import io.jsonwebtoken.Claims;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SelfIssuedJwtFilter extends OncePerRequestFilter {

    private final JwtTokenService jwtTokenService;

    public SelfIssuedJwtFilter(JwtTokenService jwtTokenService) {
        this.jwtTokenService = jwtTokenService;
    }

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request,
                                    @NotNull HttpServletResponse response,
                                    @NotNull FilterChain filterChain)
            throws ServletException, IOException {

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = extractToken(request);

        if (token != null && isSelfIssuedToken(token)) {
            try {
                Claims claims = jwtTokenService.validateToken(token);

                List<GrantedAuthority> authorities = new ArrayList<>();

                @SuppressWarnings("unchecked")
                List<String> groups = claims.get("groups", List.class);
                if (groups != null) {
                    groups.forEach(role ->
                            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.toUpperCase()))
                    );
                }

                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(
                                claims.getSubject(),
                                null,
                                authorities
                        );

                SecurityContextHolder.getContext().setAuthentication(authentication);

            } catch (Exception e) {
                logger.debug("Self-issued token validation failed", e);
            }
        }

        filterChain.doFilter(request, response);
    }

    private String extractToken(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            return header.substring(7);
        }
        return null;
    }

    private boolean isSelfIssuedToken(String token) {
        try {
            Claims claims = jwtTokenService.validateToken(token);
            String tokenType = claims.get("token_type", String.class);
            return "ext_app".equals(tokenType);
        } catch (Exception e) {
            return false;
        }
    }
}