import type { Redis } from 'ioredis';

function key(namespace: string, token: string): string {
  return `confirm:${namespace}:${token}`;
}

export async function setConfirmation<T extends object>(
  redis: Redis,
  namespace: string,
  token: string,
  entry: T,
  ttlSeconds: number
): Promise<void> {
  await redis.set(key(namespace, token), JSON.stringify(entry), 'EX', ttlSeconds);
}

export async function getConfirmation<T>(
  redis: Redis,
  namespace: string,
  token: string
): Promise<T | null> {
  const raw = await redis.get(key(namespace, token));
  if (!raw) {
    return null;
  }
  try {
    return JSON.parse(raw) as T;
  } catch {
    return null;
  }
}

export async function deleteConfirmation(
  redis: Redis,
  namespace: string,
  token: string
): Promise<void> {
  await redis.del(key(namespace, token));
}

export async function takeConfirmation<T>(
  redis: Redis,
  namespace: string,
  token: string
): Promise<T | null> {
  const k = key(namespace, token);
  const raw = await redis.get(k);
  if (!raw) {
    return null;
  }
  await redis.del(k);
  try {
    return JSON.parse(raw) as T;
  } catch {
    return null;
  }
}
