import { redirect } from '@tanstack/react-router';
import { createMiddleware } from '@tanstack/react-start';
import { getRequestHeaders } from '@tanstack/react-start/server';
import { auth } from './auth';

export const authMiddleware = createMiddleware({ type: 'function' }).server(
  async ({ next }) => {
    const headers = getRequestHeaders();
    const session = await auth.api.getSession({
      headers,
    });
    if (!session) {
      throw redirect({ to: '/sign-in' });
    }
    return await next({
      context: {
        user: {
          id: session?.user?.id,
          name: session?.user?.name,
          email: session?.user?.email,
          image: session?.user?.image,
          activeHouseId: session?.session?.activeOrganizationId,
        },
      },
    });
  },
);
