-- Migration: wallet_history + audit_log.installation_id
-- Version: 1.3.39
-- À exécuter sur OVH CloudDB

-- 1. Table wallet_history (ledger complet des mouvements de ressources)
CREATE TABLE IF NOT EXISTS `wallet_history` (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_id` int NOT NULL,
  `resource` enum('points','hints','undos','replays','bonus_points') NOT NULL,
  `delta` int NOT NULL COMMENT 'Positif = crédit, négatif = débit',
  `balance_before` int NOT NULL DEFAULT 0,
  `balance_after` int NOT NULL DEFAULT 0,
  `source` varchar(80) NOT NULL COMMENT 'wallet.reward, wallet.purchase, daily_bonus, arcade_bonus, ads.reward, ads.double_points, weekly.claim, stripe.cash, wallet.consume',
  `meta` json DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_wh_user` (`user_id`, `created_at`),
  KEY `idx_wh_source` (`source`, `created_at`),
  CONSTRAINT `wallet_history_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

-- 2. Colonne installation_id sur audit_log (traçabilité device PWA)
ALTER TABLE `audit_log`
  ADD COLUMN `installation_id` VARCHAR(64) DEFAULT NULL AFTER `meta`;
