package dev.lions.utils;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import dev.lions.models.Project;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ApplicationScoped
public class CacheService {
  private final Cache<String, Project> projectCache;

  public CacheService() {
    this.projectCache =
        CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(30, TimeUnit.MINUTES)
                    .removalListener(
                        notification -> log.debug("Cache entry removed. Key: {}, Cause: {}",
                                                  notification.getKey(), notification.getCause()))
                    .build();
  }

  public void cacheProject(String projectId, Project project) {
    projectCache.put(projectId, project);
  }

  public Optional<Project> getProjectFromCache(String projectId) {
    return Optional.ofNullable(projectCache.getIfPresent(projectId));
  }

  public void invalidateProjectCache(String projectId) {
    projectCache.invalidate(projectId);
  }
}
