import { getCloudflareContext } from "@opennextjs/cloudflare"; import { parseSurvey, type AiSurvey } from "@/lib/ai-survey"; import { parseProfile, profileRow, type LearningProfile } from "@/lib/onboarding"; import type { AccountUser } from "@/lib/session-server"; type AccountStore = { saved(): Promise; profile(): Promise; progress(): Promise; survey(): Promise; setSaved(key: string, saved: boolean): Promise; setProfile(profile: LearningProfile): Promise; setProgress(keys: string[], completed: boolean): Promise; recordView(key: string): Promise; setSurvey(survey: AiSurvey | null): Promise; }; type D1Statement = { bind(...args: (string | null)[]): D1Statement; first(): Promise; all(): Promise<{ results: T[] }>; run(): Promise; }; type D1 = { prepare(sql: string): D1Statement; batch(statements: D1Statement[]): Promise; }; type TutorialRow = { tutorial_slug: string }; type ProfileRow = { goals: string; tracks: string }; type SurveyRow = { uses: string; tools: string }; export function d1AccountStore(db: D1, user: AccountUser): AccountStore { function ensureUser(now: string) { return db.prepare(` INSERT INTO users (id, email, full_name, avatar_url, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING `).bind(user.id, user.email, user.name || null, user.image ?? null, new Date(user.createdAt).toISOString(), now); } return { async saved() { const { results } = await db.prepare( "SELECT tutorial_slug FROM saved_tutorials WHERE user_id = ? ORDER BY created_at DESC", ).bind(user.id).all(); return results.map((row) => row.tutorial_slug); }, async profile() { const row = await db.prepare("SELECT * FROM learning_profiles WHERE user_id = ?") .bind(user.id).first(); return row ? parseProfile({ ...row, goals: JSON.parse(row.goals), tracks: JSON.parse(row.tracks) }) : null; }, async progress() { const { results } = await db.prepare( "SELECT tutorial_slug FROM tutorial_activity WHERE user_id = ? AND completed_at IS NOT NULL", ).bind(user.id).all(); return results.map((row) => row.tutorial_slug); }, async survey() { const row = await db.prepare("SELECT * FROM ai_surveys WHERE user_id = ?").bind(user.id).first(); return row ? parseSurvey({ ...row, uses: JSON.parse(row.uses), tools: JSON.parse(row.tools) }) : null; }, async setSaved(key, saved) { if (!saved) { await db.prepare("DELETE FROM saved_tutorials WHERE user_id = ? AND tutorial_slug = ?").bind(user.id, key).run(); return; } const now = new Date().toISOString(); await db.batch([ensureUser(now), db.prepare(` INSERT INTO saved_tutorials (user_id, tutorial_slug, created_at) VALUES (?, ?, ?) ON CONFLICT (user_id, tutorial_slug) DO NOTHING `).bind(user.id, key, now)]); }, async setProfile(profile) { const row = profileRow(user.id, profile); await db.batch([ensureUser(row.updated_at), db.prepare(` INSERT INTO learning_profiles (user_id, goals, tracks, level, weekly_time, format, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (user_id) DO UPDATE SET goals=excluded.goals, tracks=excluded.tracks, level=excluded.level, weekly_time=excluded.weekly_time, format=excluded.format, updated_at=excluded.updated_at `).bind(row.user_id, JSON.stringify(row.goals), JSON.stringify(row.tracks), row.level, row.weekly_time, row.format, row.updated_at, row.updated_at)]); return { ...profile, updatedAt: row.updated_at }; }, async setProgress(keys, completed) { const now = new Date().toISOString(); const statements = keys.map((key) => db.prepare(` INSERT INTO tutorial_activity (user_id, tutorial_slug, completed_at) VALUES (?, ?, ?) ON CONFLICT (user_id, tutorial_slug) DO UPDATE SET completed_at=excluded.completed_at `).bind(user.id, key, completed ? now : null)); await db.batch([ensureUser(now), ...statements]); }, async recordView(key) { const now = new Date().toISOString(); await db.batch([ensureUser(now), db.prepare(` INSERT INTO tutorial_activity (user_id, tutorial_slug, view_count, first_viewed_at, last_viewed_at) VALUES (?, ?, 1, ?, ?) ON CONFLICT (user_id, tutorial_slug) DO UPDATE SET view_count=tutorial_activity.view_count+1, first_viewed_at=COALESCE(tutorial_activity.first_viewed_at, excluded.first_viewed_at), last_viewed_at=excluded.last_viewed_at `).bind(user.id, key, now, now)]); }, async setSurvey(survey) { if (!survey) { await db.prepare("DELETE FROM ai_surveys WHERE user_id = ?").bind(user.id).run(); return null; } const now = new Date().toISOString(); await db.batch([ensureUser(now), db.prepare(` INSERT INTO ai_surveys (user_id, role, uses, uses_other, tools, daily_hours, ai_years, depth, coding, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (user_id) DO UPDATE SET role=excluded.role, uses=excluded.uses, uses_other=excluded.uses_other, tools=excluded.tools, daily_hours=excluded.daily_hours, ai_years=excluded.ai_years, depth=excluded.depth, coding=excluded.coding, updated_at=excluded.updated_at `).bind(user.id, survey.role ?? null, JSON.stringify(survey.uses), survey.usesOther ?? null, JSON.stringify(survey.tools), survey.dailyHours ?? null, survey.aiYears ?? null, survey.depth ?? null, survey.coding ?? null, now, now)]); return { ...survey, updatedAt: now }; }, }; } export function accountStore(user: AccountUser): AccountStore { const { ACCOUNTS_DB } = getCloudflareContext().env as { ACCOUNTS_DB?: D1 }; if (!ACCOUNTS_DB) throw new Error("Cloudflare D1 account binding is unavailable."); return d1AccountStore(ACCOUNTS_DB, user); }