package dev.dinauer.maven.maven.token;

import at.favre.lib.crypto.bcrypt.BCrypt;
import dev.dinauer.maven.maven.token.dto.TokenCreation;
import dev.dinauer.maven.maven.token.dto.TokenSecret;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import io.vertx.core.http.HttpServerRequest;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.core.SecurityContext;

import java.time.ZonedDateTime;
import java.util.UUID;

@ApplicationScoped
public class TokenService
{
    private static final BCrypt.Hasher HASHER = BCrypt.withDefaults();

    @Inject
    TokenRepo tokenRepo;

    @Inject
    SecurityContext securityContext;

    @Transactional
    public TokenSecret create(TokenCreation tokenCreation)
    {
        String secret = UUID.randomUUID().toString();
        TokenEntity entity = new TokenEntity()
            .setName(tokenCreation.name())
            .setToken(HASHER.hashToString(11, secret.toCharArray()))
            .setUserId(securityContext.getUserPrincipal().getName())
            .setExpiresAt(tokenCreation.expiresAt())
            .setCreatedAt(ZonedDateTime.now());
        tokenRepo.persist(entity);
        return new TokenSecret(entity.getId(), tokenCreation.name(), tokenCreation.expiresAt(), secret, entity.getCreatedAt());
    }

    @Transactional
    public void delete(String id)
    {
        TokenEntity token = tokenRepo.findById(id);
        if (securityContext.getUserPrincipal().getName().equals(token.getUserId()))
        {
            tokenRepo.delete(token);
        }
    }
}
