/*
 * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). All Rights Reserved.
 *
 * This software is the property of WSO2 LLC. and its suppliers, if any.
 * Dissemination of any information or reproduction of any material contained
 * herein in any form is strictly forbidden, unless permitted by WSO2 expressly.
 * You may not alter or remove any copyright or other notice from copies of this content.
 */

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

import org.wso2.carbon.database.utils.jdbc.NamedJdbcTemplate;
import org.wso2.carbon.database.utils.jdbc.exceptions.DataAccessException;
import org.wso2.carbon.identity.core.migrate.MigrationClientException;

import static org.wso2.carbon.is.migration.service.v700.util.Utils.getNewTemplateForSharedDB;

/**
 * DAO implementation for user core.
 */
public class UserCoreDAO {

    private static final String IS_DOMAIN_EXISTING =
            "SELECT COUNT(*) FROM UM_DOMAIN WHERE UM_DOMAIN_NAME=? AND UM_TENANT_ID=?";

    /**
     * Check whether the domain exists in the tenant.
     *
     * @param domain   Domain name.
     * @param tenantID Tenant ID.
     * @return True if the domain exists in the tenant, false otherwise.
     * @throws MigrationClientException If an error occurs while checking the domain existence.
     */
    public boolean isExistingDomain(String domain, int tenantID) throws MigrationClientException {

        NamedJdbcTemplate namedJdbcTemplate = getNewTemplateForSharedDB();
        try {
            return namedJdbcTemplate.fetchSingleRecord(IS_DOMAIN_EXISTING,
                    (resultSet, rowNumber) -> resultSet.getInt(1) > 0,
                    namedPreparedStatement -> {
                        namedPreparedStatement.setString(1, domain);
                        namedPreparedStatement.setInt(2, tenantID);
                    });
        } catch (DataAccessException e) {
            throw new MigrationClientException("Error while checking domain in tenant with ID: " + tenantID, e);
        }
    }
}
