BEGIN
    DECLARE @FKIOP NVARCHAR(60)
    SELECT @FKIOP = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'IDN_OIDC_PROPERTY' AND CONSTRAINT_TYPE ='FOREIGN KEY'
    DECLARE @DropFKIOP NVARCHAR(MAX)
    SET @DropFKIOP = N'ALTER TABLE IDN_OIDC_PROPERTY DROP CONSTRAINT ' + QUOTENAME(@FKIOP)
    EXEC(@DropFKIOP)
END

BEGIN
    DECLARE @FKIOCAC VARCHAR(60)
    SELECT @FKIOCAC = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'IDN_OAUTH2_CIBA_AUTH_CODE' AND CONSTRAINT_TYPE ='FOREIGN KEY'
    DECLARE @DropFKIOCAC NVARCHAR(MAX)
    SET @DropFKIOCAC = N'ALTER TABLE IDN_OAUTH2_CIBA_AUTH_CODE DROP CONSTRAINT ' + QUOTENAME(@FKIOCAC)
    EXEC(@DropFKIOCAC)
END

DROP INDEX [IDX_IOP_CK] ON IDN_OIDC_PROPERTY;

ALTER TABLE IDN_OAUTH_CONSUMER_APPS DROP CONSTRAINT CONSUMER_KEY_CONSTRAINT;

ALTER TABLE IDN_OAUTH_CONSUMER_APPS ADD CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (TENANT_ID, CONSUMER_KEY);

ALTER TABLE IDN_OIDC_PROPERTY ADD CONSTRAINT FK_TENANT_CONSUMER_KEY_IOP_IOCA FOREIGN KEY (TENANT_ID, CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(TENANT_ID, CONSUMER_KEY) ON DELETE CASCADE;

ALTER TABLE IDN_OAUTH2_CIBA_AUTH_CODE ADD CONSTRAINT FK_TENANT_CONSUMER_KEY_IOCAC_IOCA FOREIGN KEY (TENANT_ID, CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(TENANT_ID, CONSUMER_KEY) ON DELETE CASCADE;

CREATE INDEX IDX_IOP_CK ON IDN_OIDC_PROPERTY(TENANT_ID, CONSUMER_KEY);
