-- #migration 2026_10_27_001
-- Publications automatiques d'avancees dans le Fil (CDC « Publications automatiques d'avancees dans le Fil », 17/10/2026).
--  - posts.kind : 'member' (ecrite par un membre) ou 'auto' (creee automatiquement) ; posts.auto_event : action_started | action_finished | parcours_started | parcours_finished |
--    group_started | group_finished ; posts.auto_day : le jour (heure locale du membre) pour le plafond quotidien et le regroupement. body reste NOT NULL : '' pour une publication automatique
--    (la phrase est construite a l'affichage, pas stockee).
--  - auto_post_refs : ce que chaque publication automatique designe (action ou parcours). is_group = 0 : publication individuelle, qui evolue de « demarre » a « termine » ; is_group = 1 :
--    element d'une publication GROUPEE. L'unicite (membre, element, evenement, individuel / groupe) rend la creation idempotente meme si deux requetes arrivent en meme temps.
--  - post_themes.system_key : theme reserve (« progress » = « Avancees ») : non supprimable, non desactivable, jamais propose pour une publication ecrite a la main.
--  - users.auto_posts_optin : NULL = pas encore repondu, 1 = oui, 0 = non (rien ne se publie tant que ce n'est pas 1) ; auto_posts_optin_at : date du choix (pour pouvoir justifier l'accord) ;
--    auto_posts_visibility : visibilite des publications automatiques (« all » par defaut).
ALTER TABLE posts ADD COLUMN kind VARCHAR(10) NOT NULL DEFAULT 'member', ADD COLUMN auto_event VARCHAR(30) NULL, ADD COLUMN auto_day DATE NULL, ADD KEY idx_posts_auto (user_id, kind, auto_day);
ALTER TABLE post_themes ADD COLUMN system_key VARCHAR(20) NULL;
INSERT INTO post_themes (label_fr, label_en, sort_order, active, system_key)
  SELECT 'Avancées', 'Progress', (SELECT COALESCE(MAX(t.sort_order), 0) + 1 FROM post_themes t), 1, 'progress' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM post_themes x WHERE x.system_key = 'progress');
ALTER TABLE users ADD COLUMN auto_posts_optin TINYINT(1) NULL, ADD COLUMN auto_posts_optin_at DATETIME NULL, ADD COLUMN auto_posts_visibility VARCHAR(10) NOT NULL DEFAULT 'all';
CREATE TABLE IF NOT EXISTS auto_post_refs (
  id         BIGINT      NOT NULL AUTO_INCREMENT,
  post_id    INT         NOT NULL,
  user_id    VARCHAR(64) NOT NULL,
  ref_type   VARCHAR(10) NOT NULL,
  ref_id     VARCHAR(40) NOT NULL,
  event      VARCHAR(10) NOT NULL,
  is_group   TINYINT(1)  NOT NULL DEFAULT 0,
  created_at DATETIME    NOT NULL DEFAULT UTC_TIMESTAMP(),
  PRIMARY KEY (id),
  UNIQUE KEY uq_apr (user_id, ref_type, ref_id, event, is_group),
  KEY idx_apr_post (post_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
