package com.ease.gsms.server.repositories;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.security.Principal;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

@Repository
public class ApiKeyRepository {

    @Value("${sql.users.getUsernameByApiKey}")
    private String getUsernameByApiKeySQL;

    @Value("${sql.users.getApiKeysForUsername}")
    private String getApiKeysForUsernameSQL;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public String getUsernameByApiKey(UUID apiKey) {

        // TODO: cache this

        try {
            return jdbcTemplate.queryForObject(getUsernameByApiKeySQL, String.class, apiKey);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }

    }

    public List<UUID> getApiKeysForUsername(String userName) {

        return jdbcTemplate.queryForList(getApiKeysForUsernameSQL, String.class, userName).stream().map(UUID::fromString).collect(Collectors.toList());

    }

}
