package api

import (
	"net/http"

	"github.com/gin-gonic/gin"

	_ "oci-portal/internal/oci" // swagger 注解引用
)

// ---- 控制台连接（VNC / 串口） ----

type createConsoleConnectionRequest struct {
	Region       string `json:"region"`
	SSHPublicKey string `json:"sshPublicKey" binding:"required"`
}

// @Summary  创建实例控制台连接
// @Tags     计算
// @Param    id path int true "配置 ID"
// @Param    instanceId path string true "instanceId"
// @Param    body body createConsoleConnectionRequest true "请求体"
// @Success  201 {object} oci.ConsoleConnection
// @Security BearerAuth
// @Router   /api/v1/oci-configs/{id}/instances/{instanceId}/console-connections [post]
func (h *ociConfigHandler) createConsoleConnection(c *gin.Context) {
	id, ok := pathID(c)
	if !ok {
		return
	}
	var req createConsoleConnectionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	conn, err := h.svc.CreateConsoleConnection(c.Request.Context(), id, req.Region, c.Param("instanceId"), req.SSHPublicKey)
	if err != nil {
		respondError(c, err)
		return
	}
	c.JSON(http.StatusCreated, conn)
}

// @Summary  实例控制台连接列表
// @Tags     计算
// @Param    id path int true "配置 ID"
// @Param    instanceId path string true "instanceId"
// @Success  200 {array} oci.ConsoleConnection
// @Security BearerAuth
// @Router   /api/v1/oci-configs/{id}/instances/{instanceId}/console-connections [get]
func (h *ociConfigHandler) listConsoleConnections(c *gin.Context) {
	id, ok := pathID(c)
	if !ok {
		return
	}
	connections, err := h.svc.ConsoleConnections(c.Request.Context(), id, c.Query("region"), c.Param("instanceId"))
	if err != nil {
		respondError(c, err)
		return
	}
	c.JSON(http.StatusOK, connections)
}

// @Summary  删除实例控制台连接
// @Tags     计算
// @Param    id path int true "配置 ID"
// @Param    connectionId path string true "connectionId"
// @Success  204 "无内容"
// @Security BearerAuth
// @Router   /api/v1/oci-configs/{id}/console-connections/{connectionId} [delete]
func (h *ociConfigHandler) deleteConsoleConnection(c *gin.Context) {
	id, ok := pathID(c)
	if !ok {
		return
	}
	if err := h.svc.DeleteConsoleConnection(c.Request.Context(), id, c.Query("region"), c.Param("connectionId")); err != nil {
		respondError(c, err)
		return
	}
	c.Status(http.StatusNoContent)
}
