#pragma once

#include "pch.h"
#include "CertificateManager.h"

namespace SSLClient {

/// <summary>
/// SSL客户端类
/// 封装SSL连接、数据发送接收功能
/// </summary>
class SSLClientConnection
{
public:
	SSLClientConnection();
	~SSLClientConnection();

	// 禁止拷贝
	SSLClientConnection(const SSLClientConnection&) = delete;
	SSLClientConnection& operator=(const SSLClientConnection&) = delete;

	/// <summary>
	/// 初始化SSL环境
	/// </summary>
	/// <param name="clientCert">客户端证书PEM</param>
	/// <param name="clientKey">客户端私钥PEM</param>
	/// <param name="caCert">CA证书PEM</param>
	/// <param name="keyPassword">私钥密码</param>
	/// <returns>成功返回true</returns>
	bool Initialize(const char* clientCert, const char* clientKey, 
	                const char* caCert, const char* keyPassword);

	/// <summary>
	/// 连接到服务器
	/// </summary>
	/// <param name="address">服务器地址</param>
	/// <param name="port">服务器端口</param>
	/// <returns>成功返回true</returns>
	bool Connect(const char* address, int port);

	/// <summary>
	/// 发送数据
	/// </summary>
	/// <param name="data">要发送的数据</param>
	/// <returns>成功返回true</returns>
	bool Send(const std::string& data);

	/// <summary>
	/// 接收数据（非阻塞）
	/// </summary>
	/// <param name="buffer">接收缓冲区</param>
	/// <param name="bufferSize">缓冲区大小</param>
	/// <returns>接收到的字节数，-1表示错误，0表示没有数据</returns>
	int Receive(char* buffer, int bufferSize);

	/// <summary>
	/// 断开连接
	/// </summary>
	void Disconnect();

	/// <summary>
	/// 检查是否已连接
	/// </summary>
	bool IsConnected() const { return m_isConnected; }

	/// <summary>
	/// 获取使用的加密套件
	/// </summary>
	const char* GetCipherSuite() const;

private:
	/// <summary>
	/// 初始化Winsock
	/// </summary>
	bool InitializeWinsock();

	/// <summary>
	/// 清理资源
	/// </summary>
	void Cleanup();

private:
	SSL_CTX* m_sslContext;
	SSL* m_ssl;
	SOCKET m_socket;
	bool m_isConnected;
	CertificateManager m_certManager;
};

} // namespace SSLClient
