package service

import (
	"context"
	"fmt"
	"strings"

	"oci-portal/internal/oci"
)

// CreateConsoleConnection 为实例创建控制台连接（VNC / 串口）。
// OCI 控制台连接只接受 RSA 公钥，ed25519 等类型会被拒绝。
func (s *OciConfigService) CreateConsoleConnection(ctx context.Context, id uint, region, instanceID, sshPublicKey string) (oci.ConsoleConnection, error) {
	if sshPublicKey == "" {
		return oci.ConsoleConnection{}, fmt.Errorf("create console connection: sshPublicKey is required")
	}
	if !strings.HasPrefix(strings.TrimSpace(sshPublicKey), "ssh-rsa ") {
		return oci.ConsoleConnection{}, fmt.Errorf("create console connection: only ssh-rsa public keys are supported by OCI console connections")
	}
	cred, err := s.credentialsByID(ctx, id)
	if err != nil {
		return oci.ConsoleConnection{}, err
	}
	return s.client.CreateConsoleConnection(ctx, cred, region, instanceID, sshPublicKey)
}

// ConsoleConnections 列出实例的控制台连接。
func (s *OciConfigService) ConsoleConnections(ctx context.Context, id uint, region, instanceID string) ([]oci.ConsoleConnection, error) {
	cred, err := s.credentialsByID(ctx, id)
	if err != nil {
		return nil, err
	}
	return s.client.ListConsoleConnections(ctx, cred, region, instanceID)
}

// DeleteConsoleConnection 删除控制台连接。
func (s *OciConfigService) DeleteConsoleConnection(ctx context.Context, id uint, region, connectionID string) error {
	cred, err := s.credentialsByID(ctx, id)
	if err != nil {
		return err
	}
	return s.client.DeleteConsoleConnection(ctx, cred, region, connectionID)
}
