import { createMiddleware } from "hono/factory";
import { getCookie } from "hono/cookie";
import { findSession } from "../db/queries.js";

export type AuthUser = {
  id: number;
  username: string;
  email: string;
  displayName: string | null;
};

type Variables = { user: AuthUser | null };

export const sessionMiddleware = createMiddleware<{ Variables: Variables }>(
  async (c, next) => {
    const sessionId = getCookie(c, "pijulab_session");
    if (sessionId) {
      const row = await findSession(sessionId);
      if (row) {
        c.set("user", {
          id: row.id,
          username: row.username,
          email: row.email,
          displayName: row.display_name,
        });
      } else {
        c.set("user", null);
      }
    } else {
      c.set("user", null);
    }
    await next();
  },
);

export const requireAuth = createMiddleware<{ Variables: Variables }>(
  async (c, next) => {
    const user = c.get("user");
    if (!user) {
      return c.json({ message: "Unauthorized" }, 401);
    }
    await next();
  },
);