import { and, eq } from "drizzle-orm";
import type { AnalyticsEvent } from "@app/analytics";
import type { Database } from "./client.js";
import { schema } from "./index.js";

/**
 * Track a product analytics event server-side if the user has opted in.
 * Moved to @app/database so both API routes and workers can write events
 * without depending on apps/api internals.
 */
export async function trackProductAnalytics(
  db: Database,
  userId: string,
  event: AnalyticsEvent,
): Promise<void> {
  const optedIn = await db
    .select({ status: schema.userConsents.status })
    .from(schema.userConsents)
    .where(
      and(
        eq(schema.userConsents.userId, userId),
        eq(schema.userConsents.kind, "product_analytics"),
      ),
    )
    .limit(1);
  if (optedIn[0] && optedIn[0].status !== "granted") return;

  await db.insert(schema.productAnalyticsEvents).values({
    occurredAt: event.occurredAt ? new Date(event.occurredAt) : new Date(),
    receivedAt: new Date(),
    eventName: event.name,
    anonymousId: event.anonymousId ?? null,
    sessionId: event.sessionId ?? null,
    userId,
    householdId: event.householdId ?? null,
    appVersion: event.appVersion ?? null,
    platform: event.platform ?? null,
    locale: event.locale ?? null,
    experimentVariant: event.experimentVariant ?? null,
    properties: event.properties ?? {},
  });
}
