/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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.apache.camel.quarkus.component.sftp.it;

import java.nio.file.Files;
import java.nio.file.Path;

import io.quarkus.runtime.Startup;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;

/**
 * Manages SSH certificates for SFTP integration tests.
 * Uses certificates generated by the containerized SFTP test resource.
 */
@ApplicationScoped
@Startup
public class SftpCertificateManager {
    private static final Logger LOGGER = Logger.getLogger(SftpCertificateManager.class);

    private Path certsDir;

    public SftpCertificateManager() {
        try {
            initializeCertificates();
        } catch (Exception e) {
            throw new RuntimeException("Failed to initialize SFTP certificates", e);
        }
    }

    private void initializeCertificates() throws Exception {
        LOGGER.info("Setting up SFTP certificate files from test resource");

        Path classpathCerts = Path.of("target", "classes", "certs");
        Files.createDirectories(classpathCerts);

        certsDir = classpathCerts;

        String userKeyPath = System.getProperty("sftp.test.user.key");
        String userCertPath = System.getProperty("sftp.test.user.cert");

        if (userKeyPath == null || userCertPath == null) {
            throw new IllegalStateException(
                    "Certificate paths not set. Test resource not started? sftp.test.user.key=" + userKeyPath
                            + ", sftp.test.user.cert=" + userCertPath);
        }

        byte[] privateKeyBytes = Files.readAllBytes(Path.of(userKeyPath));
        byte[] certificateBytes = Files.readAllBytes(Path.of(userCertPath));

        Files.write(classpathCerts.resolve("test-key-rsa.key"), privateKeyBytes);
        Files.write(classpathCerts.resolve("test-key-rsa-cert.pub"), certificateBytes);

        LOGGER.infof("SFTP certificate files created in: %s", classpathCerts);
    }

    public Path getCertsDir() {
        return certsDir;
    }

    public byte[] getUserPrivateKeyBytes() {
        try {
            String path = System.getProperty("sftp.test.user.key");
            if (path == null) {
                throw new IllegalStateException("Certificate path not set. Test resource not started?");
            }
            return Files.readAllBytes(Path.of(path));
        } catch (Exception e) {
            throw new RuntimeException("Failed to read user private key bytes", e);
        }
    }

    public byte[] getUserCertificateBytes() {
        try {
            String path = System.getProperty("sftp.test.user.cert");
            if (path == null) {
                throw new IllegalStateException("Certificate path not set. Test resource not started?");
            }
            return Files.readAllBytes(Path.of(path));
        } catch (Exception e) {
            throw new RuntimeException("Failed to read user certificate bytes", e);
        }
    }
}
