USE util;

CREATE TABLE notification(
    id INT PRIMARY KEY,
    `name` VARCHAR(255) UNIQUE,
    `description` VARCHAR(255)
);

CREATE TABLE notificationAcl(
    notificationFk INT, -- FK notification.id
    roleFk INT(10) unsigned, -- FK account.role.id
    PRIMARY KEY(notificationFk, roleFk)
);

ALTER TABLE `util`.`notificationAcl` ADD CONSTRAINT `notificationAcl_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `util`.`notification` (`id`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

ALTER TABLE `util`.`notificationAcl` ADD CONSTRAINT `notificationAcl_ibfk_2` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role`(`id`)
  ON DELETE RESTRICT
  ON UPDATE CASCADE;

CREATE TABLE notificationSubscription(
    notificationFk INT, -- FK notification.id
    userFk INT(10) unsigned, -- FK account.user.id
    PRIMARY KEY(notificationFk, userFk)
);

ALTER TABLE `util`.`notificationSubscription` ADD CONSTRAINT `notificationSubscription_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `util`.`notification` (`id`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

ALTER TABLE `util`.`notificationSubscription` ADD CONSTRAINT `notificationSubscription_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES  `account`.`user`(`id`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

CREATE TABLE notificationQueue(
    id INT PRIMARY KEY AUTO_INCREMENT,
    notificationFk VARCHAR(255), -- FK notification.name
    params TEXT, -- JSON
    authorFk INT(10) unsigned NULL, -- FK account.user.id
    `status` ENUM('pending', 'sent', 'error') NOT NULL DEFAULT 'pending',
    created DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX(notificationFk),
    INDEX(authorFk),
    INDEX(status)
);

ALTER TABLE `util`.`notificationQueue` ADD CONSTRAINT `nnotificationQueue_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `util`.`notification` (`name`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

ALTER TABLE `util`.`notificationQueue` ADD CONSTRAINT `notificationQueue_ibfk_2` FOREIGN KEY (`authorFk`) REFERENCES `account`.`user`(`id`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

CREATE TABLE notificationConfig(
    id INT PRIMARY KEY AUTO_INCREMENT,
    cleanDays MEDIUMINT
);

INSERT INTO notificationConfig
    SET cleanDays = 90;
