import { db } from "~/server/db";
import { sessions, users } from "~/server/db/schema/auth";
import { eq, and, gt } from "drizzle-orm";

const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000;

export async function createSession(
  userId: string,
): Promise<typeof sessions.$inferSelect> {
  const token = crypto.randomUUID();
  const expires = new Date(Date.now() + SEVEN_DAYS_MS);
  const [session] = await db
    .insert(sessions)
    .values({ userId, sessionToken: token, expires })
    .returning();
  return session;
}

export async function validateSession(
  sessionToken: string,
): Promise<{ session: typeof sessions.$inferSelect; user: typeof users.$inferSelect } | null> {
  const [result] = await db
    .select({ session: sessions, user: users })
    .from(sessions)
    .where(
      and(
        eq(sessions.sessionToken, sessionToken),
        gt(sessions.expires, new Date()),
      ),
    )
    .innerJoin(users, eq(sessions.userId, users.id))
    .limit(1);

  return result ?? null;
}
