/*
 * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com).
 *
 * WSO2 LLC. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.wso2.carbon.is.migration.service.v600.dao;

import org.wso2.carbon.identity.core.migrate.MigrationClientException;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class IdentityProviderDAO {

    private static final String UPDATE_IDP_WITH_ROLE_CLAIM_MAPPING = "UPDATE IDP_CLAIM_MAPPING SET LOCAL_CLAIM = " +
            "'http://wso2.org/claims/roles' WHERE LOCAL_CLAIM = 'http://wso2.org/claims/role'";

    private static final String UPDATE_IDP_WITH_ROLE_CLAIM = "UPDATE IDP SET ROLE_CLAIM_URI = " +
            "'http://wso2.org/claims/roles' WHERE ROLE_CLAIM_URI = 'http://wso2.org/claims/role'";

    public void migrateRoleClaimMapping() throws MigrationClientException {

        try (Connection connection = IdentityDatabaseUtil.getDBConnection(true)) {
            try (PreparedStatement preparedStatement =
                         connection.prepareStatement(UPDATE_IDP_WITH_ROLE_CLAIM_MAPPING)) {
                preparedStatement.executeUpdate();
                IdentityDatabaseUtil.commitTransaction(connection);
            }
        } catch (SQLException e) {
            throw new MigrationClientException("Error while updating role claim mapping.", e);

        }
    }

    public void migrateRoleClaim() throws MigrationClientException {

        try (Connection connection = IdentityDatabaseUtil.getDBConnection(true)) {
            try (PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_IDP_WITH_ROLE_CLAIM)) {
                preparedStatement.executeUpdate();
                IdentityDatabaseUtil.commitTransaction(connection);
            }
        } catch (SQLException e) {
            throw new MigrationClientException("Error while updating role claim.", e);
        }
    }
}
