/**
 * Ma vérification, écrite indépendamment. On mesure la diffusion, on remet.
 */
import { eq, sql } from "drizzle-orm"

import { db } from "@/lib/db/client"
import { domainEvents, notifications, people, taskInstances, recurringTemplates } from "@/lib/db/schema"

const [base] = await db.select({ e: sql<number>`count(*)::int` }).from(domainEvents)
const [nb] = await db.select({ n: sql<number>`count(*)::int` }).from(notifications)
console.log("état de départ :", { evenements: base?.e, notifications: nb?.n })

const statuses = await db
  .select({ s: taskInstances.status, n: sql<number>`count(*)::int` })
  .from(taskInstances)
  .groupBy(taskInstances.status)
  .orderBy(taskInstances.status)
console.log("statuts :", statuses)

// Le texte est-il stocké en clé ou en phrase ?
console.log()
console.log("=== la colonne qui porte le texte ===")
const cols = await db.execute(sql`
  select column_name, data_type from information_schema.columns
  where table_name = 'notifications' order by ordinal_position
`)
console.log(cols)

// Une transaction annulée ne doit rien laisser.
console.log()
try {
  await db.transaction(async (tx) => {
    const [t] = await tx.select({ id: taskInstances.id }).from(taskInstances).limit(1)
    await tx.insert(domainEvents).values({
      type: "task.reminded",
      taskInstanceId: t!.id,
      actorPersonId: null,
      payload: { note: "sonde" },
    })
    throw new Error("annulation volontaire")
  })
} catch {
  /* attendu */
}
const [after] = await db.select({ e: sql<number>`count(*)::int` }).from(domainEvents)
console.log("après une transaction annulée :", after?.e, "événements")

void people
void recurringTemplates
void eq
process.exit(0)
