package org.keycloak.connections.mongo.updater.impl.updates;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import org.keycloak.models.KeycloakSession;

/**
 * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
 */
public class Update1_2_0_RC1 extends Update {

    @Override
    public String getId() {
        return "1.2.0.RC1";
    }

    @Override
    public void update(KeycloakSession session) {
        deleteEntries("clientSessions");
        deleteEntries("sessions");

        convertApplicationsToClients();
        convertOAuthClientsToClients();

        db.getCollection("realms").update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("adminAppId", "clientId")), false, true);

        ensureIndex("userConsents", new String[]{"clientId", "userId"}, true, false);
    }

    private void convertApplicationsToClients() {
        DBCollection applications = db.getCollection("applications");
        applications.update(new BasicDBObject(), new BasicDBObject("$set", new BasicDBObject("consentRequired", false)), false, true);
        applications.update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("name", "clientId")), false, true);
        renameCollection("applications", "clients");
        log.debugv("Converted applications to clients");

        DBCollection roles = db.getCollection("roles");
        roles.update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("applicationId", "clientId")), false, true);
        log.debugv("Renamed roles.applicationId to roles.clientId");

        db.getCollection("clients").dropIndex("realmId_1_name_1");
        ensureIndex("clients", new String[]{"realmId", "clientId"}, true, false);

    }

    private void convertOAuthClientsToClients() {
        DBCollection clients = db.getCollection("clients");
        DBCollection oauthClients = db.getCollection("oauthClients");
        oauthClients.update(new BasicDBObject(), new BasicDBObject("$rename", new BasicDBObject("name", "clientId")), false, true);
        oauthClients.update(new BasicDBObject(), new BasicDBObject("$set", new BasicDBObject("consentRequired", true)), false, true);

        DBCursor curs = oauthClients.find();
        while (curs.hasNext()) {
            clients.insert(curs.next());
        }

        oauthClients.drop();
        log.debugv("Converted oauthClients to clients");
    }

}

@@ -737,32 +737,41 @@
 minAppId%22, %22
-c
+masterAdminC
 lient
-Id
 %22)), false, 
@@ -983,32 +983,85 @@
 applications%22);%0A
+        applications.dropIndex(%22realmId_1_name_1%22);%0A%0A
         applicat
@@ -1686,75 +1686,8 @@
 );%0A%0A
-        db.getCollection(%22clients%22).dropIndex(%22realmId_1_name_1%22);%0A
     
@@ -1760,25 +1760,24 @@
 ue, false);%0A
-%0A
     %7D%0A%0A    p
@@ -1943,32 +1943,85 @@
 oauthClients%22);%0A
+        oauthClients.dropIndex(%22realmId_1_name_1%22);%0A%0A
         oauthCli

Fix mongo migration