/**
 * Tenant audit log schema — tenant-audit-log spec.
 *
 * Immutable, append-only record of write-level actions within a workspace.
 * Entries are inserted asynchronously via the audit-log-queue consumer Worker;
 * mutation handlers fire-and-forget via logAuditEvent().
 *
 * Design decisions:
 * - No CHECK on event_type: deliberately open — future event types must insert.
 * - No GIN on metadata: filters never touch metadata content (SELECT-only JSONB).
 * - before_state/after_state: operational-audit-trail (spec 50) diff columns.
 *   Both nullable — before_state NULL for create events, after_state NULL for delete.
 * - Four B-tree indexes covering the four primary query shapes.
 * - idx_tal_entity_history partial index is in raw SQL migration (not drizzle index() builder).
 */
import { pgTable, uuid, text, jsonb, timestamp, index } from 'drizzle-orm/pg-core'
import { tenants } from './tenants'
import { users } from './users'

export const tenantAuditLog = pgTable(
  'tenant_audit_log',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    userId: uuid('user_id').references(() => users.id, { onDelete: 'set null' }),
    actorName: text('actor_name'),
    actorEmail: text('actor_email'),
    eventType: text('event_type').notNull(),
    entityType: text('entity_type'),
    entityId: uuid('entity_id'),
    entityLabel: text('entity_label'),
    metadata: jsonb('metadata').$type<Record<string, unknown>>(),
    ipAddress: text('ip_address'),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    // operational-audit-trail (spec 50): diff columns — nullable JSONB
    beforeState: jsonb('before_state').$type<Record<string, unknown> | null>(),
    afterState:  jsonb('after_state').$type<Record<string, unknown> | null>(),
  },
  (t) => ({
    tenantTimeIdx: index('idx_tal_tenant_time').on(t.tenantId, t.createdAt.desc()),
    entityIdx: index('idx_tal_entity').on(t.tenantId, t.entityType, t.entityId),
    userIdx: index('idx_tal_user').on(t.tenantId, t.userId),
    eventTypeIdx: index('idx_tal_event_type').on(t.tenantId, t.eventType),
  }),
)

export type TenantAuditLogRow = typeof tenantAuditLog.$inferSelect
export type NewTenantAuditLog = typeof tenantAuditLog.$inferInsert
