import { auth } from "@haushaltsApp/auth";
import { createMiddleware } from "hono/factory";

type Session = Awaited<ReturnType<typeof auth.api.getSession>>;

export type AuthVariables = {
  user: NonNullable<Session>["user"] | null;
  session: NonNullable<Session>["session"] | null;
};

export const authMiddleware = createMiddleware<{ Variables: AuthVariables }>(
  async (c, next) => {
    const result = await auth.api.getSession({
      headers: c.req.raw.headers,
    });
    c.set("user", result?.user ?? null);
    c.set("session", result?.session ?? null);
    await next();
  }
);

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