import { parseJson } from '@/common/utils/json'; import { getDatabase } from '@/remote/database'; import type { Day, FoodRecommendation } from '@/types/foodlog'; import * as Crypto from 'expo-crypto'; function rowToDay(row: Record): Day { return { id: row.id as string, profileId: row.profile_id as string, date: row.date as string, recommendedIngredients: parseJson(row.recommended_ingredients, undefined), recommendedFoods: parseJson(row.recommended_foods, undefined), }; } export type SaveDayInput = { profileId: string; date: string; ingredients: string[]; foods: FoodRecommendation[]; }; export async function getDay(profileId: string, date: string): Promise { const db = getDatabase(); const result = await db.getOptional>( 'SELECT * FROM days WHERE profile_id = ? AND date = ?', [profileId, date] ); if (result) return rowToDay(result); const demoResult = await db.getOptional>( 'SELECT * FROM days WHERE profile_id = ? AND date = ?', ['demo', date] ); if (demoResult) return rowToDay(demoResult); return null; } export async function saveDay(input: SaveDayInput): Promise { const db = getDatabase(); const existing = await getDay(input.profileId, input.date); const now = new Date().toISOString(); if (existing) { await db.execute( `UPDATE days SET recommended_ingredients = ?, recommended_foods = ?, last_edit_time = ? WHERE id = ?`, [JSON.stringify(input.ingredients), JSON.stringify(input.foods), now, existing.id] ); return existing.id; } const id = Crypto.randomUUID(); await db.execute( `INSERT INTO days (id, profile_id, date, recommended_ingredients, recommended_foods, creation_time, last_edit_time) VALUES (?, ?, ?, ?, ?, ?, ?)`, [ id, input.profileId, input.date, JSON.stringify(input.ingredients), JSON.stringify(input.foods), now, now, ] ); return id; } export async function clearCache(profileId: string, date: string): Promise { const db = getDatabase(); await db.execute( 'UPDATE days SET recommended_ingredients = NULL, recommended_foods = NULL WHERE profile_id = ? AND date = ?', [profileId, date] ); }