CREATE TABLE IF NOT EXISTS gateway_audit_logs (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  category text NOT NULL DEFAULT 'system',
  action text NOT NULL,
  actor_gateway_user_id uuid REFERENCES gateway_users(id) ON DELETE SET NULL,
  actor_user_id text,
  actor_username text,
  actor_source text,
  actor_roles jsonb NOT NULL DEFAULT '[]'::jsonb,
  target_type text NOT NULL,
  target_id text NOT NULL,
  target_gateway_user_id uuid REFERENCES gateway_users(id) ON DELETE SET NULL,
  target_gateway_tenant_id uuid REFERENCES gateway_tenants(id) ON DELETE SET NULL,
  request_ip text,
  user_agent text,
  before_state jsonb NOT NULL DEFAULT '{}'::jsonb,
  after_state jsonb NOT NULL DEFAULT '{}'::jsonb,
  metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_gateway_audit_logs_category_created
  ON gateway_audit_logs(category, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_gateway_audit_logs_action_created
  ON gateway_audit_logs(action, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_gateway_audit_logs_target
  ON gateway_audit_logs(target_type, target_id, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_gateway_audit_logs_actor
  ON gateway_audit_logs(actor_gateway_user_id, created_at DESC);
