-- Injection automatique d'un VOID si aucun événement valide
CREATE OR REPLACE FUNCTION inject_void_if_needed()
RETURNS VOID AS $$
DECLARE
  void_id TEXT;
  now_ts TIMESTAMPTZ := now();
  pubkey TEXT;
BEGIN
  SELECT pubkey INTO pubkey FROM core_identity WHERE active LIMIT 1;

  IF NOT EXISTS (SELECT 1 FROM events WHERE block_id IS NULL) THEN
    void_id := 'void-' || to_char(now_ts, 'YYYYMMDDHH24MISS');
    INSERT INTO events (
      event_id, block_id, payload, author_pubkey, signature, timestamp
    ) VALUES (
      void_id,
      NULL,
      '{"type": "void", "reason": "no valid events"}',
      pubkey,
      'signature_placeholder',
      now_ts
    );
  END IF;
END;
$$ LANGUAGE plpgsql;

-- Vérifie que tous les blocs ont au moins 1 événement associé
CREATE OR REPLACE FUNCTION check_block_event_integrity()
RETURNS TABLE(block_id INTEGER, event_count INTEGER) AS $$
BEGIN
  RETURN QUERY
    SELECT b.block_id, COUNT(e.event_id)
    FROM blocks b
    LEFT JOIN events e ON e.block_id = b.block_id
    GROUP BY b.block_id
    HAVING COUNT(e.event_id) = 0;
END;
$$ LANGUAGE plpgsql;