/*
 * Copyright (c) 2024, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed 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.migrator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.identity.core.migrate.MigrationClientException;
import org.wso2.carbon.is.migration.service.Migrator;
import org.wso2.carbon.is.migration.service.v530.util.JDBCPersistenceUtil;
import org.wso2.carbon.is.migration.util.Schema;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;

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

/**
 * TOTPClaimDataMigrator for adding data related to totpEnabled claim in IS 6.0.0.
 */
public class TOTPClaimDataMigrator extends Migrator {

    private static final Logger log = LoggerFactory.getLogger(TOTPClaimDataMigrator.class);

    private static final String SET_TOTP_ENABLED_CLAIM_SQL = "INSERT INTO IDN_IDENTITY_USER_DATA " +
            "(TENANT_ID, USER_NAME, DATA_KEY, DATA_VALUE) SELECT TENANT_ID, USER_NAME, ?, ? " +
            "FROM IDN_IDENTITY_USER_DATA WHERE DATA_KEY = ? AND DATA_VALUE IS NOT NULL;";
    private static final String SET_TOTP_ENABLED_CLAIM_SQL_ORACLE = "INSERT INTO IDN_IDENTITY_USER_DATA " +
            "(TENANT_ID, USER_NAME, DATA_KEY, DATA_VALUE) SELECT TENANT_ID, USER_NAME, ?, ? " +
            "FROM IDN_IDENTITY_USER_DATA WHERE DATA_KEY = ? AND DATA_VALUE IS NOT NULL";

    private static final String TOTP_ENABLED_CLAIM_URI = "http://wso2.org/claims/identity/totpEnabled";
    private static final String SECRET_KEY_CLAIM_URI = "http://wso2.org/claims/identity/secretkey";

    @Override
    public void migrate() throws MigrationClientException {

        migrateTOTPEnabledClaimData();
    }

    @Override
    public void dryRun() throws MigrationClientException {

        log.info("Dry run capability not implemented in {} migrator.", this.getClass().getName());
    }

    private void migrateTOTPEnabledClaimData() throws MigrationClientException {

        log.info("Started migrating user data for " + TOTP_ENABLED_CLAIM_URI + " claim");
        try (Connection connection = getDataSource(Schema.IDENTITY.getName()).getConnection()) {
            String databaseType = DatabaseCreator.getDatabaseType(connection);
            boolean isOracleDB = "oracle".equals(databaseType);
            boolean autoCommitStatus = connection.getAutoCommit();
            connection.setAutoCommit(false);

            try (PreparedStatement preparedStatement = connection.prepareStatement(
                    isOracleDB ? SET_TOTP_ENABLED_CLAIM_SQL_ORACLE : SET_TOTP_ENABLED_CLAIM_SQL)) {
                preparedStatement.setString(1, TOTP_ENABLED_CLAIM_URI);
                preparedStatement.setString(2, "true");
                preparedStatement.setString(3, SECRET_KEY_CLAIM_URI);
                preparedStatement.executeUpdate();
            } catch (SQLException e) {
                JDBCPersistenceUtil.rollbackTransaction(connection);
                connection.setAutoCommit(autoCommitStatus);
                throw new MigrationClientException("An error occurred while updating user data for the claim " +
                        TOTP_ENABLED_CLAIM_URI, e);
            }

            JDBCPersistenceUtil.commitTransaction(connection);
            connection.setAutoCommit(autoCommitStatus);
            log.info("Migrating user data for " + TOTP_ENABLED_CLAIM_URI + " claim is complete.");
        } catch (SQLException e) {
            throw new MigrationClientException("An error occurred while updating user data for the claim " +
                    TOTP_ENABLED_CLAIM_URI, e);
        } catch (Exception e) {
            throw new MigrationClientException("An error occurred while getting the database type", e);
        }
    }
}
