/**
 * Tử Vi Số · Usage counters
 *
 * Server-side counter for daily AI quota. We piggyback on the existing
 * `AIMessage` and `ToolHistory` tables — no new schema needed for counting:
 *   - aiSectionsPerDay → ToolHistory rows where toolKey starts with
 *     "ai-section:" within the past 24h
 *   - aiChatMessagesPerDay → AIMessage rows authored by the user within
 *     past 24h
 *
 * Both queries use index-friendly `gte: rolling24h` filters on createdAt.
 *
 * If new table pressure becomes a concern, swap in a UserDailyQuota table
 * with date-keyed counters. For < 10k users a Prisma count() is fine.
 */
import { prisma } from "@/lib/db";

const DAY_MS = 24 * 60 * 60 * 1000;

function rolling24hAgo(): Date {
  return new Date(Date.now() - DAY_MS);
}

export async function countAiSectionsLast24h(userId: string): Promise<number> {
  return prisma.toolHistory.count({
    where: {
      userId,
      toolKey: { startsWith: "ai-section:" },
      createdAt: { gte: rolling24hAgo() },
    },
  });
}

export async function countAiChatMessagesLast24h(userId: string): Promise<number> {
  return prisma.aIMessage.count({
    where: {
      role: "user",
      conversation: { userId },
      createdAt: { gte: rolling24hAgo() },
    },
  });
}

/**
 * Record a tool/quota usage event. Idempotent against duplicates only by
 * the row insert order — caller must ensure each call corresponds to one
 * billable action. We use ToolHistory because the schema already supports
 * arbitrary toolKey strings.
 */
export async function logAiSectionUsage(userId: string, section: string): Promise<void> {
  await prisma.toolHistory.create({
    data: {
      userId,
      toolKey: `ai-section:${section}`,
      inputJson: { section },
      resultJson: {},
    },
  });
}
