package com.platform2easy.genesis.infra.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.platform2easy.genesis.domain.model.AppUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

@Service("infraTokenService")
public class TokenService {

    @Value("${api.security.token.secret}")
    private String secret;

    public String generateToken(AppUser user) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withIssuer("genesis")
                .withSubject(user.getUserEmail())
                .withClaim("role_id", user.getRoleId())
                .withClaim("company_id", user.getCompanyId())
                .withExpiresAt(Instant.now().plus(2, ChronoUnit.HOURS))
                .sign(algorithm);
    }

    public String getSubject(String token) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        DecodedJWT decoded = JWT.require(algorithm)
                .withIssuer("genesis")
                .build()
                .verify(token);
        return decoded.getSubject();
    }
    
    public boolean validateToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWT.require(algorithm)
                .withIssuer("genesis")
                .build()
                .verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
