import { randomUUID } from "node:crypto";
import {
  HOST_PUBLIC_SESSION_PREFIX,
  HOST_PUBLIC_SESSION_TTL_SECONDS,
} from "@/lib/constants/host-public-api";
import { getRedis } from "@/lib/redis";
import type { HostPublicSessionPayload } from "@/modules/host/types";

function sessionKey(id: string): string {
  return `${HOST_PUBLIC_SESSION_PREFIX}${id}`;
}

export async function saveHostPublicSession(
  payload: Omit<HostPublicSessionPayload, "created_at">,
): Promise<string> {
  const id = randomUUID();
  const record: HostPublicSessionPayload = {
    ...payload,
    created_at: new Date().toISOString(),
  };
  await getRedis().setex(
    sessionKey(id),
    HOST_PUBLIC_SESSION_TTL_SECONDS,
    JSON.stringify(record),
  );
  return id;
}

export async function loadHostPublicSession(
  id: string,
): Promise<HostPublicSessionPayload | null> {
  const raw = await getRedis().get(sessionKey(id));
  if (!raw) {
    return null;
  }
  return JSON.parse(raw) as HostPublicSessionPayload;
}

export async function deleteHostPublicSession(id: string): Promise<void> {
  await getRedis().del(sessionKey(id));
}
