/*
 * Copyright (c) 2025, 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.v700.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.identity.core.migrate.MigrationClientException;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;
import org.wso2.carbon.is.migration.service.v700.dao.IdPDAO;

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

/**
 * Service for adding idp id for existing federated session mappings.
 */
public class FederateSessionMappingService {

    private static final Logger LOG = LoggerFactory.getLogger(FederateSessionMappingService.class);
    private static final IdPDAO idPDAO = new IdPDAO();
    private static final String ID = "ID";
    private static final String IDP_NAME = "IDP_NAME";
    private static final String TENANT_ID = "TENANT_ID";

    public void execute() throws MigrationClientException {

        migrateFederatedSessionMappings();
    }

    private void migrateFederatedSessionMappings() throws MigrationClientException {

        try (Connection identityConnection = IdentityDatabaseUtil.getDBConnection(true)) {
            // Get all federated session mappings.
            PreparedStatement selectFederatedSessionMappingsPS =
                    identityConnection.prepareStatement(IdPDAO.SELECT_ALL_FEDERATED_SESSION_MAPPINGS);
            ResultSet selectFederatedSessionMappingsRS = selectFederatedSessionMappingsPS.executeQuery();

            while (selectFederatedSessionMappingsRS.next()) {
                int federatedSessionMappingId = Integer.parseInt(selectFederatedSessionMappingsRS.getString(ID));
                String idpName = selectFederatedSessionMappingsRS.getString(IDP_NAME);
                int tenantId = Integer.parseInt(selectFederatedSessionMappingsRS.getString(TENANT_ID));

                // Get idp id using idp name and tenant id.
                int idpId = idPDAO.getIdpIdByNameAndTenantId(idpName, tenantId);
                if (idpId == -1) {
                    LOG.error("IDP with name: {} does not exist for tenant id: {}", idpName, tenantId);
                    continue;
                }

                // Set idp id for federated session mapping.
                idPDAO.setIdpIdForFederatedSessionMapping(federatedSessionMappingId, idpId);
            }
        } catch (SQLException e) {
            throw new MigrationClientException("Error while migrating the federated session mappings.", e);
        }
    }
}
