ALTER TABLE IDN_OAUTH2_ACCESS_TOKEN_AUDIT ADD ID INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (ID);

ALTER TABLE IDN_OAUTH2_SCOPE_BINDING ADD ID INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (ID);

ALTER TABLE IDN_AUTH_USER_SESSION_MAPPING ADD ID INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (ID);

ALTER TABLE IDN_OAUTH2_CIBA_REQUEST_SCOPES ADD ID INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (ID);

-- Add CONSENTED_TOKEN column if it doesn't exist.
DROP PROCEDURE IF EXISTS ALTER_IDN_OAUTH2_ACCESS_TOKEN;

DELIMITER $$
CREATE PROCEDURE ALTER_IDN_OAUTH2_ACCESS_TOKEN()
BEGIN
    IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='IDN_OAUTH2_ACCESS_TOKEN') THEN
        IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='IDN_OAUTH2_ACCESS_TOKEN' AND COLUMN_NAME='CONSENTED_TOKEN') THEN
            ALTER TABLE `IDN_OAUTH2_ACCESS_TOKEN` ADD COLUMN `CONSENTED_TOKEN` VARCHAR(6);
        END IF;
    END IF;
END $$
DELIMITER ;

CALL ALTER_IDN_OAUTH2_ACCESS_TOKEN();

ALTER TABLE IDN_FED_AUTH_SESSION_MAPPING DROP PRIMARY KEY;
ALTER TABLE IDN_FED_AUTH_SESSION_MAPPING ADD ID INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (ID);
ALTER TABLE IDN_FED_AUTH_SESSION_MAPPING ADD TENANT_ID INTEGER DEFAULT 0 NOT NULL;
ALTER TABLE IDN_FED_AUTH_SESSION_MAPPING ADD UNIQUE(IDP_SESSION_ID, TENANT_ID);
