import { defineAction } from "@agent-native/core/action"; import { and, eq } from "drizzle-orm"; import { z } from "zod"; import { db, schema } from "../server/db/index.js"; import { quoteFavoriteCounter, withActionSpan } from "../server/otel.js"; export default defineAction({ description: "Favorite or unfavorite a quote for a given visitor (toggles based on current state). Returns the new favorited state and total favorite count for the quote.", schema: z.object({ quoteId: z.coerce.number().int().describe("The quote's id"), visitorId: z.string().min(1).describe("Anonymous visitor id (from browser storage)"), }), run: async (args) => { return withActionSpan( "toggle-favorite", { quoteId: args.quoteId }, async () => { const existing = await db() .select() .from(schema.favorites) .where( and( eq(schema.favorites.quote_id, args.quoteId), eq(schema.favorites.visitor_id, args.visitorId), ), ) .limit(1); let favorited: boolean; if (existing.length > 0) { await db().delete(schema.favorites).where(eq(schema.favorites.id, existing[0].id)); favorited = false; quoteFavoriteCounter.add(1, { action: "remove" }); } else { await db().insert(schema.favorites).values({ quote_id: args.quoteId, visitor_id: args.visitorId, }); favorited = true; quoteFavoriteCounter.add(1, { action: "add" }); } const allFavorites = await db() .select() .from(schema.favorites) .where(eq(schema.favorites.quote_id, args.quoteId)); return { quoteId: args.quoteId, favorited, favoriteCount: allFavorites.length }; }, ); }, });