import { defineTable } from 'convex/server';
import { v } from 'convex/values';

export const agentWebhooksTable = defineTable({
  organizationId: v.string(),
  agentSlug: v.string(),
  token: v.string(),
  isActive: v.boolean(),
  lastTriggeredAt: v.optional(v.number()),
  createdAt: v.number(),
  /** Display value (email or user _id) shown in admin UIs. */
  createdBy: v.string(),
  /**
   * Better Auth user ID of the webhook creator, used as the `userId` on
   * threads generated by this webhook so the creator sees them in their
   * chat history. Optional for backward-compat with rows created before
   * this field existed (those threads remain owned by `webhook:<id>` and
   * won't show up in any human user's history).
   */
  createdByUserId: v.optional(v.string()),
})
  .index('by_org', ['organizationId'])
  .index('by_agent', ['organizationId', 'agentSlug'])
  .index('by_token', ['token']);

/**
 * Maps a hashed client-supplied `user` field (from OpenAI ChatCompletion body)
 * to a stable conversation thread for a given agent webhook, so that repeated
 * POSTs with the same `user` land in the same agent thread (e.g. follow-up
 * turns for a forked Meetily that sets `user: <meeting-uuid>`).
 *
 * Row is inserted lazily by `getOrCreateUserThread`. Cascade-deleted when the
 * webhook or the mapped thread is removed.
 */
export const agentWebhookUserThreadsTable = defineTable({
  webhookId: v.id('agentWebhooks'),
  organizationId: v.string(),
  userHash: v.string(),
  threadId: v.string(),
  createdAt: v.number(),
})
  .index('by_webhookId_userHash', ['webhookId', 'userHash'])
  .index('by_threadId', ['threadId'])
  .index('by_organizationId', ['organizationId']);
