import { desc } from 'drizzle-orm'
import { index, jsonb, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'

export const auditLog = pgTable(
  'audit_log',
  {
    id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
    actorId: text('actor_id'),
    actorType: text('actor_type'),
    actorLabel: text('actor_label'),
    action: text('action').notNull(),
    entityType: text('entity_type').notNull(),
    entityId: text('entity_id').notNull(),
    metadata: jsonb('metadata').$type<Record<string, unknown> | null>(),
    ip: text('ip'),
    tenantId: text('tenant_id'),
    // precision:3 (ms) — keyset cursor round-trips through a JS Date (ms); native µs
    // would drop same-ms rows across page boundaries (see boundary spec amendment A).
    createdAt: timestamp('created_at', { withTimezone: true, precision: 3 }).notNull().$defaultFn(() => new Date()),
  },
  (table) => [
    index('audit_log_tenant_created_idx').on(table.tenantId, desc(table.createdAt)),
    index('audit_log_tenant_entity_idx').on(table.tenantId, table.entityType, table.entityId),
    index('audit_log_tenant_actor_idx').on(table.tenantId, table.actorId),
  ],
)

export const auditSchema = {
  auditLog,
}

export type AuditSchema = typeof auditSchema
