CREATE TABLE `abonnements_push` (
	`id` int unsigned AUTO_INCREMENT NOT NULL,
	`utilisateur_id` int unsigned NOT NULL,
	`app` enum('admin','client','auditeur') NOT NULL,
	`session_id` char(64) NOT NULL,
	`empreinte` char(64) NOT NULL,
	`adresse` varchar(1000) NOT NULL,
	`p256dh` varchar(100) NOT NULL,
	`auth` varchar(40) NOT NULL,
	`echecs` int unsigned NOT NULL DEFAULT 0,
	`vu_le` datetime NOT NULL,
	`cree_le` datetime NOT NULL,
	CONSTRAINT `abonnements_push_id` PRIMARY KEY(`id`),
	CONSTRAINT `uq_abonnements_empreinte` UNIQUE(`empreinte`)
);
--> statement-breakpoint
CREATE TABLE `rappels` (
	`id` int unsigned AUTO_INCREMENT NOT NULL,
	`utilisateur_id` int unsigned NOT NULL,
	`cle` varchar(100) NOT NULL,
	`cree_le` datetime NOT NULL,
	CONSTRAINT `rappels_id` PRIMARY KEY(`id`),
	CONSTRAINT `uq_rappels` UNIQUE(`utilisateur_id`,`cle`)
);
--> statement-breakpoint
ALTER TABLE `onboarding` MODIFY COLUMN `type` enum('info','position','photo','installation','notifications') NOT NULL DEFAULT 'info';--> statement-breakpoint
ALTER TABLE `notifications` ADD `pousse_le` datetime;--> statement-breakpoint
ALTER TABLE `abonnements_push` ADD CONSTRAINT `abonnements_push_utilisateur_id_utilisateurs_id_fk` FOREIGN KEY (`utilisateur_id`) REFERENCES `utilisateurs`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE `rappels` ADD CONSTRAINT `rappels_utilisateur_id_utilisateurs_id_fk` FOREIGN KEY (`utilisateur_id`) REFERENCES `utilisateurs`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX `ix_abonnements_utilisateur` ON `abonnements_push` (`utilisateur_id`);--> statement-breakpoint
CREATE INDEX `ix_abonnements_session` ON `abonnements_push` (`session_id`);--> statement-breakpoint
CREATE INDEX `ix_rappels_cree` ON `rappels` (`cree_le`);--> statement-breakpoint
CREATE INDEX `ix_notifications_envoi` ON `notifications` (`pousse_le`,`cree_le`);--> statement-breakpoint
UPDATE `notifications` SET `pousse_le` = `cree_le` WHERE `pousse_le` IS NULL;--> statement-breakpoint
INSERT INTO `onboarding` (`type`, `titre`, `texte`, `ordre`, `actif`, `cree_le`, `maj_le`) SELECT 'notifications', 'Restez prévenu', 'Nouvelles missions, corrections demandées et rappels, même application fermée.', MAX(`ordre`) + 1, true, UTC_TIMESTAMP(), UTC_TIMESTAMP() FROM `onboarding` HAVING COUNT(*) > 0;
