import { createKV } from "./create-kv.js";

type Session = { id: string; userId: string; expiresAt: string; createdAt: string };
type User = { id: string; username: string; email: string; passwordHash: string; role: "customer" | "owner"; createdAt: string };

export const sessionsKV = createKV<Session>("sessions");
export const usersKV = createKV<User>("users");

export async function assertOwner(sessionId: string): Promise<void> {
  const session = await sessionsKV.getItem(sessionId);
  if (!session) throw new Error("Invalid session");
  if (new Date(session.expiresAt) < new Date()) throw new Error("Session expired");
  const user = await usersKV.getItem(session.userId);
  if (!user || user.role !== "owner") throw new Error("Forbidden");
}


