CREATE TABLE IF NOT EXISTS `nagiosxi` . `xi_sso_mappings` (
    `id` int unsigned NOT NULL AUTO_INCREMENT,
    `object_id` varchar(255) NOT NULL,
    `client_id` varchar(255) NOT NULL,
    `user_id` int NOT NULL,
    `tenant_id` varchar(255) NOT NULL,
    `source` enum('individual','group','both') NOT NULL DEFAULT 'individual',
    `priority` enum('individual','group') NOT NULL DEFAULT 'individual',
    `source_group_id` varchar(255) DEFAULT NULL,
    `created_via_sso` tinyint(1) NOT NULL DEFAULT 0,
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `last_sync_at` timestamp NULL DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_object_client` (`object_id`, `client_id`),
    KEY `idx_user_id` (`user_id`),
    KEY `idx_source_priority` (`source`, `priority`),
    KEY `idx_group_id` (`source_group_id`),
    CONSTRAINT `fk_sso_user` FOREIGN KEY (`user_id`) REFERENCES `nagiosxi`.`xi_users` (`user_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `nagiosxi` . `xi_sso_group_config` (
    `id` int unsigned NOT NULL AUTO_INCREMENT,
    `group_id` varchar(255) NOT NULL,
    `client_id` varchar(255) NOT NULL,
    `account_mode` enum('individual','shared') NOT NULL,
    `xi_user_id` int DEFAULT NULL,
    `config_json` text NOT NULL,
    `member_count` int unsigned DEFAULT 0,
    `last_sync_at` timestamp NULL DEFAULT NULL,
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_group_client` (`group_id`, `client_id`),
    KEY `idx_client_id` (`client_id`),
    KEY `idx_xi_user` (`xi_user_id`),
    CONSTRAINT `fk_group_sso_user` FOREIGN KEY (`xi_user_id`) REFERENCES `nagiosxi`.`xi_users` (`user_id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

GRANT ALL ON `nagiosxi`.`xi_sso_group_config` TO 'nagiosxi'@'USERDATABASE';
GRANT ALL ON `nagiosxi`.`xi_sso_mappings` TO 'nagiosxi'@'USERDATABASE';