package de.oaa.libredeck.web.service;

import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class JobStore {

    private static final long TTL_MS = 10 * 60 * 1000; // 10 minutes

    private final ConcurrentHashMap<String, GenerationJob> jobs = new ConcurrentHashMap<>();

    public GenerationJob create() {
        evictExpired();
        GenerationJob job = new GenerationJob(UUID.randomUUID().toString());
        jobs.put(job.id, job);
        return job;
    }

    public Optional<GenerationJob> get(String id) {
        return Optional.ofNullable(jobs.get(id));
    }

    public void remove(String id) {
        jobs.remove(id);
    }

    private void evictExpired() {
        long cutoff = System.currentTimeMillis() - TTL_MS;
        jobs.entrySet().removeIf(e -> e.getValue().createdAt < cutoff);
    }
}
