/*
 * 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.v710.migrator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.admin.advisory.mgt.dao.AdminAdvisoryBannerDAO;
import org.wso2.carbon.admin.advisory.mgt.dto.AdminAdvisoryBannerDTO;
import org.wso2.carbon.admin.advisory.mgt.exception.AdminAdvisoryMgtException;
import org.wso2.carbon.identity.core.migrate.MigrationClientException;
import org.wso2.carbon.identity.core.persistence.registry.RegistryResourceMgtService;
import org.wso2.carbon.identity.core.persistence.registry.RegistryResourceMgtServiceImpl;
import org.wso2.carbon.identity.system.config.mgt.advisory.DBBasedAdminBannerDAO;
import org.wso2.carbon.is.migration.service.Migrator;
import org.wso2.carbon.registry.core.Resource;

import java.util.Optional;

import static org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;

/**
 * This class is to migrate the admin advisory banner configuration.
 */
public class AdminAdvisoryBannerMigrator extends Migrator {

    private static final Logger LOG = LoggerFactory.getLogger(AdminAdvisoryBannerMigrator.class);

    private final RegistryResourceMgtService resourceMgtService = new RegistryResourceMgtServiceImpl();
    private AdminAdvisoryBannerDAO dbBasedAdminBannerDAO = new DBBasedAdminBannerDAO();

    private static final String ADMIN_ADVISORY_BANNER_PATH = "identity/config/adminAdvisoryBanner";
    private static final String ENABLE_BANNER = "enableBanner";
    private static final String BANNER_CONTENT = "bannerContent";

    @Override
    public void dryRun() throws MigrationClientException {

        LOG.info("RDM-RLC-DR>> Residual data migration (dry run) of admin advisory banner configs started.");
        migrateAdminBannerConfigs(true);
    }

    @Override
    public void migrate() throws MigrationClientException {

        LOG.info("RDM-AAB>> Residual data migration of admin advisory banner configs started.");
        migrateAdminBannerConfigs(false);
    }

    private void migrateAdminBannerConfigs(boolean isDryRun) throws MigrationClientException {

        try {
            if (dbBasedAdminBannerDAO.loadAdminAdvisoryConfig(SUPER_TENANT_DOMAIN_NAME).isPresent()) {
                LOG.warn("RDM-AAB>> Admin advisory banner configs already exists in database. Skipping migration from " +
                        "registry.");
                return;
            }

            Optional<AdminAdvisoryBannerDTO> adminAdvisoryConfig = loadAdminAdvisoryConfig(SUPER_TENANT_DOMAIN_NAME);
            if (adminAdvisoryConfig.isPresent()) {
                if (!isDryRun) {
                    dbBasedAdminBannerDAO.saveAdminAdvisoryConfig(adminAdvisoryConfig.get(), SUPER_TENANT_DOMAIN_NAME);
                    LOG.info("RDM-AAB>> Admin advisory banner config migration completed successfully.");
                } else {
                    LOG.info("RDM-AAB>> Admin advisory banner config migration skipped due to dry run.");
                }
            } else {
                LOG.info("RDM-AAB>> No admin advisory banner config migration found in registry.");
            }
        } catch (AdminAdvisoryMgtException e) {
            throw new MigrationClientException("Error while migrating admin advisory banner configs to the new DAO", e);
        }
    }

    private Optional<AdminAdvisoryBannerDTO> loadAdminAdvisoryConfig(String tenantDomain) {

        Resource resource = resourceMgtService.getIdentityResource(ADMIN_ADVISORY_BANNER_PATH, tenantDomain);
        if (resource == null) {
            return Optional.empty();
        }

        AdminAdvisoryBannerDTO adminAdvisoryBanner = createAdminAdvisoryBannerDTO(resource);
        return Optional.of(adminAdvisoryBanner);
    }

    private AdminAdvisoryBannerDTO createAdminAdvisoryBannerDTO(Resource bannerResource) {

        String enableBanner = bannerResource.getProperty(ENABLE_BANNER);
        String content = bannerResource.getProperty(BANNER_CONTENT);

        AdminAdvisoryBannerDTO adminAdvisoryBannerDTO = new AdminAdvisoryBannerDTO();
        adminAdvisoryBannerDTO.setEnableBanner(Boolean.parseBoolean(enableBanner));
        adminAdvisoryBannerDTO.setBannerContent(content);
        return adminAdvisoryBannerDTO;
    }
}
