import { ObjectId } from "mongodb"; import { getDb } from "@/lib/db"; export type AiAnalysisTargetType = "running" | "strength" | "dashboard"; export type AiAnalysisInput = { userId: string; targetType: AiAnalysisTargetType; targetId: ObjectId; summary: string; tips: string[]; model: string; }; export type AiAnalysis = AiAnalysisInput & { _id: ObjectId; createdAt: Date; }; export type SerializedAiAnalysis = { _id: string; targetType: AiAnalysisTargetType; targetId: string; summary: string; tips: string[]; model: string; createdAt: string; }; export function serializeAnalysis(analysis: AiAnalysis): SerializedAiAnalysis { return { _id: analysis._id.toString(), targetType: analysis.targetType, targetId: analysis.targetId.toString(), summary: analysis.summary, tips: analysis.tips, model: analysis.model, createdAt: analysis.createdAt.toISOString(), }; } const COLLECTION = "ai_analyses"; const DASHBOARD_TARGET_ID = new ObjectId("000000000000000000000001"); async function getCollection() { const db = await getDb(); return db.collection(COLLECTION); } export async function saveAiAnalysis(input: AiAnalysisInput): Promise { const collection = await getCollection(); const doc = { ...input, _id: new ObjectId(), createdAt: new Date() }; await collection.insertOne(doc); return doc; } export async function getLatestAnalysisForTarget( userId: string, targetType: AiAnalysisTargetType, targetId: ObjectId ): Promise { const collection = await getCollection(); return collection.findOne({ userId, targetType, targetId }, { sort: { createdAt: -1 } }); } export async function getDashboardAnalysis(userId: string): Promise { const collection = await getCollection(); return collection.findOne( { userId, targetType: "dashboard", targetId: DASHBOARD_TARGET_ID }, { sort: { createdAt: -1 } } ); } export async function saveDashboardAnalysis( userId: string, summary: string, tips: string[], model: string ): Promise { return saveAiAnalysis({ userId, targetType: "dashboard", targetId: DASHBOARD_TARGET_ID, summary, tips, model, }); }