/**
 * community blueprint · wiring seam for `@platform-modules/audit`.
 *
 * Adapter-minimalism (CLAUDE.md §4): stand up the audit_log table on an in-memory pglite and hand
 * back a Querier the module's logAudit/listAudit write/read through. A real host registers audit's
 * schema into its own Drizzle migration set.
 *
 * Community is SINGLE-SCOPE — rows are written with `tenant_id` null (the module documents this as
 * the single-tenant form) and the composition test lists by `entityType`/`action`, not by tenant.
 * (Identical stand-up to saas-admin/wiring/audit.ts; the difference is purely how the host scopes the
 * read.)
 */
import { PGlite } from '@electric-sql/pglite'
import { drizzle } from 'drizzle-orm/pglite'
import { auditSchema, type AuditSchema } from '@platform-modules/audit'
import type { Querier } from '@platform-modules/db'

export type AuditDb = Querier<AuditSchema>

export async function createAuditDb(): Promise<AuditDb> {
  const client = new PGlite()
  const db = drizzle(client, { schema: auditSchema }) as unknown as AuditDb

  await client.exec(`
    CREATE TABLE audit_log (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      actor_id text,
      actor_type text,
      actor_label text,
      action text NOT NULL,
      entity_type text NOT NULL,
      entity_id text NOT NULL,
      metadata jsonb,
      ip text,
      tenant_id text,
      created_at timestamptz(3) NOT NULL DEFAULT NOW()
    );
    CREATE INDEX audit_log_tenant_created_idx ON audit_log (tenant_id, created_at DESC);
    CREATE INDEX audit_log_tenant_entity_idx ON audit_log (tenant_id, entity_type, entity_id);
  `)

  return db
}
