import { decrypt } from "@/lib/cipher";
import { NotAuthenticated, Unauthorised } from "@/lib/error";
import { verifySession } from "@/lib/session";
import type { Context, Next } from "hono";
import { getCookie } from "hono/cookie";

export async function authMiddleware(ctx: Context, next: Next) {
  if (ctx.req.path === "/v1/member/session/rotate") {
    return await next();
  }
  const session = getCookie(ctx, "k_session");
  const sessionId = getCookie(ctx, "k_session_id");
  if (!sessionId) {
    throw new Unauthorised();
  }
  if (!session) {
    throw new NotAuthenticated();
  }
  const decryptedSession = decrypt(session);
  const isValidSession = await verifySession(decryptedSession);
  if (!isValidSession) {
    throw new NotAuthenticated();
  }
  await next();
}
