interface IdempotentEntry {
  key: string;
  scope: string;
  value: unknown;
  expiresAt: number;
}

const store = new Map<string, IdempotentEntry>();

export function makeIdempotencyKey(scope: string, key: string): string {
  return `${scope}:${key}`;
}

export function readIdempotency(scope: string, key: string): unknown | null {
  const entry = store.get(makeIdempotencyKey(scope, key));
  if (!entry) {
    return null;
  }

  if (entry.expiresAt < Date.now()) {
    store.delete(makeIdempotencyKey(scope, key));
    return null;
  }

  return entry.value;
}

export function writeIdempotency(scope: string, key: string, value: unknown, ttlMs: number): void {
  store.set(makeIdempotencyKey(scope, key), {
    key,
    scope,
    value,
    expiresAt: Date.now() + ttlMs
  });
}

export function clearIdempotency(scope: string, key: string): void {
  store.delete(makeIdempotencyKey(scope, key));
}
