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

const taskStatus = v.union(v.literal('open'), v.literal('ready'), v.literal('done'));
const decision = v.union(v.literal('clear'), v.literal('resistant'));

export default defineSchema({
  /**
   * The synced task collection. Glide is local-first: the device's MMKV store is the
   * working source of truth, and this table is the account-scoped sync target (see
   * docs/engineering/convex-sync.md).
   *
   * Identity is the client-generated `clientId` (a UUID), not the Convex `_id` — that's
   * what makes pushes idempotent (upsert by `(ownerId, clientId)`) and lets offline-created
   * rows reconcile without a round-trip. `updatedAt` is the last-write-wins key; `deletedAt`
   * is a soft-delete tombstone so deletes propagate.
   */
  tasks: defineTable({
    ownerId: v.string(), // account scope — a fixed constant in single-user mode, the auth identity later
    clientId: v.string(), // client-generated UUID — the cross-device identity
    title: v.string(),
    status: taskStatus,
    resistance: v.number(),
    exposureCount: v.number(),
    createdAt: v.number(),
    updatedAt: v.number(), // last-write-wins key
    lastDecision: v.optional(decision),
    completedAt: v.optional(v.number()),
    deletedAt: v.optional(v.number()), // tombstone
  })
    .index('by_owner_client', ['ownerId', 'clientId']) // upsert target (one row per owner+client)
    .index('by_owner_updated', ['ownerId', 'updatedAt']), // owner scan / incremental pulls
});
