/*
Copyright (c) 2026 Huawei Technologies Co., Ltd.
openFuyao is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/

package remote

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	"gitcode.com/openFuyao/ub-ssu-csi/pkg/backend"
)

// HTTP client timeout constants.
const httpClientTimeoutSec = 30 * time.Second

// Config describes TLS materials and address required to connect to UBSE service.
type Config struct {
	// ServerAddr is the address of the UBSE server (e.g., "https://ubse-server:8443").
	ServerAddr string
	// CACert is the CA certificate for TLS verification.
	CACert []byte
	// ClientCert is the client certificate for TLS authentication.
	ClientCert []byte
	// ClientKey is the client private key for TLS authentication.
	ClientKey []byte
}

// New creates a backend.StorageManager from Config.
func New(config *Config) (backend.StorageManager, error) {
	cert, err := tls.X509KeyPair(config.ClientCert, config.ClientKey)
	if err != nil {
		return nil, fmt.Errorf("load client cert/key: %w", err)
	}

	caCertPool := x509.NewCertPool()
	if !caCertPool.AppendCertsFromPEM(config.CACert) {
		return nil, fmt.Errorf("failed to append CA cert")
	}

	httpClient := &http.Client{
		Timeout: httpClientTimeoutSec,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				Certificates: []tls.Certificate{cert},
				RootCAs:      caCertPool,
			},
		},
	}

	ubseHTTPClient := NewHTTPClientBuilder(config.ServerAddr).
		WithHTTPClient(httpClient).
		Build()

	return &remoteClient{
		httpClient: ubseHTTPClient,
	}, nil
}

// NewFromDir loads TLS materials from directory and creates backend.StorageManager.
func NewFromDir(dir string) (backend.StorageManager, error) {
	config, err := LoadConfigFromDir(dir)
	if err != nil {
		return nil, fmt.Errorf("load config from dir: %w", err)
	}
	return New(config)
}

// LoadConfigFromDir reads serverAddr/ca.crt/client.crt/client.key from directory.
func LoadConfigFromDir(dir string) (*Config, error) {
	config := &Config{}

	serverAddr, err := os.ReadFile(filepath.Join(dir, "serverAddr"))
	if err != nil {
		return nil, fmt.Errorf("read serverAddr: %w", err)
	}
	config.ServerAddr = strings.TrimSpace(string(serverAddr))

	caCert, err := os.ReadFile(filepath.Join(dir, "ca.crt"))
	if err != nil {
		return nil, fmt.Errorf("read ca.crt: %w", err)
	}
	config.CACert = caCert

	clientCert, err := os.ReadFile(filepath.Join(dir, "client.crt"))
	if err != nil {
		return nil, fmt.Errorf("read client.crt: %w", err)
	}
	config.ClientCert = clientCert

	clientKey, err := os.ReadFile(filepath.Join(dir, "client.key"))
	if err != nil {
		return nil, fmt.Errorf("read client.key: %w", err)
	}
	config.ClientKey = clientKey

	return config, nil
}