CREATE TABLE IF NOT EXISTS expense_document_history (
  id TEXT PRIMARY KEY,
  document_id TEXT NOT NULL REFERENCES expense_documents(id) ON DELETE CASCADE,
  from_status TEXT,
  to_status TEXT NOT NULL,
  action TEXT NOT NULL CHECK (action IN ('created', 'submitted', 'approved', 'rejected', 'posted', 'payment', 'status_changed')),
  actor_id TEXT,
  actor_name TEXT,
  note TEXT,
  details JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_expense_document_history_document ON expense_document_history (document_id, created_at);