-- Audit automatique des insertions/modifications d'événements
CREATE TABLE event_log (
  log_id SERIAL PRIMARY KEY,
  event_id TEXT,
  action TEXT,
  timestamp TIMESTAMPTZ DEFAULT now(),
  info JSONB
);

CREATE OR REPLACE FUNCTION log_event_activity()
RETURNS TRIGGER AS $$
BEGIN
  INSERT INTO event_log (event_id, action, info)
  VALUES (
    NEW.event_id,
    TG_OP,
    row_to_json(NEW)::jsonb
  );
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_event_audit
AFTER INSERT OR UPDATE ON events
FOR EACH ROW
EXECUTE FUNCTION log_event_activity();

-- Sécurité minimale sur la présence d'une signature dans les blocs
CREATE OR REPLACE FUNCTION check_block_signature()
RETURNS TRIGGER AS $$
BEGIN
  IF NEW.signature IS NULL OR length(NEW.signature) < 64 THEN
    RAISE EXCEPTION '❌ Bloc % sans signature valide', NEW.block_id;
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_block_signature
BEFORE INSERT ON blocks
FOR EACH ROW
EXECUTE FUNCTION check_block_signature();