import type { IOauth1Token } from "garmin-connect/dist/garmin/types"; import { getDb } from "@/lib/db"; import type { GarminPendingMfa } from "@/lib/garmin/sso"; const AUTH_COLLECTION = "garmin_auth"; const PENDING_COLLECTION = "garmin_login_pending"; const CREDENTIALS_COLLECTION = "garmin_credentials"; type GarminAuthDoc = { _id: string; oauth1Token: IOauth1Token; updatedAt: Date }; type GarminPendingDoc = { _id: string; state: GarminPendingMfa; createdAt: Date }; type GarminCredentialsDoc = { _id: string; email: string; password: string }; export async function getSavedOauth1Token(userId: string): Promise { const db = await getDb(); const doc = await db.collection(AUTH_COLLECTION).findOne({ _id: userId }); return doc?.oauth1Token ?? null; } export async function saveOauth1Token(userId: string, oauth1Token: IOauth1Token): Promise { const db = await getDb(); await db .collection(AUTH_COLLECTION) .updateOne({ _id: userId }, { $set: { oauth1Token, updatedAt: new Date() } }, { upsert: true }); } export async function savePendingMfaState(userId: string, state: GarminPendingMfa): Promise { const db = await getDb(); await db .collection(PENDING_COLLECTION) .updateOne({ _id: userId }, { $set: { state, createdAt: new Date() } }, { upsert: true }); } export async function getPendingMfaState(userId: string): Promise { const db = await getDb(); const doc = await db.collection(PENDING_COLLECTION).findOne({ _id: userId }); return doc?.state ?? null; } export async function clearPendingMfaState(userId: string): Promise { const db = await getDb(); await db.collection(PENDING_COLLECTION).deleteOne({ _id: userId }); } export async function getGarminCredentials( userId: string ): Promise<{ email: string; password: string } | null> { const db = await getDb(); const doc = await db .collection(CREDENTIALS_COLLECTION) .findOne({ _id: userId }); if (!doc) return null; return { email: doc.email, password: doc.password }; } export async function saveGarminCredentials( userId: string, email: string, password: string ): Promise { const db = await getDb(); await db .collection(CREDENTIALS_COLLECTION) .updateOne({ _id: userId }, { $set: { email, password } }, { upsert: true }); }