-- #migration 2026_09_19_001
-- Crée la table de stockage du lexique généré automatiquement

CREATE TABLE IF NOT EXISTS lexique_cartes (
    id         INT AUTO_INCREMENT PRIMARY KEY,
    content_md LONGTEXT NOT NULL,
    nb_cartes  INT NOT NULL DEFAULT 0,
    generated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Seed initial — sera écrasé au premier import
INSERT INTO lexique_cartes (content_md, nb_cartes, generated_at)
SELECT
    CONCAT(
        '> Lexique initialisé par migration — regénérer via POST /admin-lexique\n',
        '> Total : ', COUNT(*), ' cartes\n\n',
        GROUP_CONCAT(
            CONCAT(
                '### ', c.id, ' — ', c.title, '\n',
                '- **Catégorie** : ', COALESCE(cat.label, '—'), '\n',
                '- **Lien** : https://uluana.art/actions/', c.slug, '\n',
                '- **Points** : ', COALESCE(c.points, '—'), '\n',
                '- **Objectif** : ', COALESCE(LEFT(c.objective, 300), '—'), '\n'
            )
            ORDER BY cat.sort_order, c.id
            SEPARATOR '\n'
        )
    ),
    COUNT(*),
    NOW()
FROM cards c
LEFT JOIN categories cat ON cat.id = c.category_id;
