package com.iqser.red.persistence.service.v1.external.api.impl.service;

import java.util.UUID;

import org.springframework.stereotype.Service;

import com.iqser.red.persistence.service.v1.external.api.impl.model.OneTimeToken;
import com.iqser.red.service.persistence.management.v1.processor.exception.BadRequestException;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class OneTimeTokenService {

    private final OneTimeTokenCacheService oneTimeTokenCacheService;


    public OneTimeToken createToken(String storageId, String userId) {

        var ott = new OneTimeToken(UUID.randomUUID().toString(), System.currentTimeMillis(), storageId, userId);
        oneTimeTokenCacheService.cacheOTT(ott.getTokenId(), ott);
        return ott;
    }


    public OneTimeToken getToken(String tokenId) {

        var token = oneTimeTokenCacheService.getToken(tokenId);
        if (token != null) {
            // older than 10 seconds
            if (System.currentTimeMillis() - token.getCreationTimestamp() > 10_000) {
                throw new BadRequestException("Invalid token: " + tokenId);
            }

            // evict token from cache on read ( one time use, duh )
            oneTimeTokenCacheService.evictToken(tokenId);
            return token;
        } else {
            throw new BadRequestException("Invalid token: " + tokenId);
        }
    }

}
