package io.gmss.fiscad.security;

import io.gmss.fiscad.entities.user.User;
import io.gmss.fiscad.paylaods.JwtAuthenticationResponse;
import io.gmss.fiscad.paylaods.UserResponse;
import io.gmss.fiscad.repositories.user.UserRepository;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class TokenAuthentificationProvider {

    private static final Logger logger = LoggerFactory.getLogger(TokenAuthentificationProvider.class);

    @Value("${jwt.jwtSecret}")
    private String jwtSecret;

    @Value("${jwt.jwtExpirationInMs}")
    private long jwtExpirationInMs;

    private final UserRepository userRepository;

    public TokenAuthentificationProvider(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    public JwtAuthenticationResponse generateToken(Authentication authentication) {
        return generateToken((UserPrincipal) authentication.getPrincipal());
    }

    public JwtAuthenticationResponse generateToken(UserDetails userDetails) {

        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);

        Map<String, Object> claims = new HashMap<>();
        List<String> roles = new ArrayList<>();
        userDetails.getAuthorities().forEach(role -> roles.add(role.getAuthority()));
        //claims.put("roles", roles);
        User user = userRepository.findByUsername(userDetails.getUsername()).get();
        claims.put("user", getUserResponseFromUser(user));
        // JWT for authentication
        String token = Jwts.builder()
                .setClaims(claims)
                .setSubject(userDetails.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, jwtSecret.getBytes())
                .compact();

        return new JwtAuthenticationResponse(token, expiryDate);
    }

    UserResponse getUserResponseFromUser(User user) {
        return new UserResponse(
                user.getId(),
                user.getNom(),
                user.getPrenom(),
                user.getTel(),
                user.getEmail(),
                user.getUsername(),
                user.isActive(),
                user.isResetPassword(),
                user.getRoles(),
                user.getStructure(),
                user.getIdCampagneCourant(),
                user.getIdSecteurCourant());

    }

    public String getUsernameFromJWT(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(jwtSecret.getBytes())
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    public boolean validateToken(String authToken) {
        return validateJWT(authToken, jwtSecret);
    }

    private boolean validateJWT(String authToken, String jwtRefreshSecret) {
        try {
            Jwts.parser().setSigningKey(jwtRefreshSecret.getBytes()).parseClaimsJws(authToken);
            return true;
        } catch (SignatureException ex) {
            logger.error("Invalid JWT signature");
        } catch (MalformedJwtException ex) {
            logger.error("Invalid JWT token");
        } catch (ExpiredJwtException ex) {
            logger.error("Expired JWT token");
        } catch (UnsupportedJwtException ex) {
            logger.error("Unsupported JWT token");
        } catch (IllegalArgumentException ex) {
            logger.error("JWT claims string is empty.");
        }
        return false;
    }
}
