package api

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

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

	"oci-portal/internal/oci"
)

// listRegions 返回本地维护的完整区域表（含友好名称），不发起云端请求。
//
// @Summary  返回本地维护的完整区域表
// @Tags     租户配置
// @Success  200 {array} oci.RegionInfo
// @Security BearerAuth
// @Router   /api/v1/regions [get]
func listRegions(c *gin.Context) {
	regions, err := oci.AllRegions()
	if err != nil {
		respondError(c, err)
		return
	}
	c.JSON(http.StatusOK, regions)
}

// @Summary  区域订阅列表
// @Tags     租户配置
// @Param    id path int true "配置 ID"
// @Success  200 {array} service.RegionSubscriptionView
// @Security BearerAuth
// @Router   /api/v1/oci-configs/{id}/region-subscriptions [get]
func (h *ociConfigHandler) regionSubscriptions(c *gin.Context) {
	id, ok := pathID(c)
	if !ok {
		return
	}
	subs, err := h.svc.RegionSubscriptions(c.Request.Context(), id)
	if err != nil {
		respondError(c, err)
		return
	}
	c.JSON(http.StatusOK, subs)
}

type subscribeRegionRequest struct {
	RegionKey string `json:"regionKey" binding:"required"`
}

// @Summary  订阅新区域
// @Tags     租户配置
// @Param    id path int true "配置 ID"
// @Param    body body subscribeRegionRequest true "请求体"
// @Success  200 {array} service.RegionSubscriptionView
// @Security BearerAuth
// @Router   /api/v1/oci-configs/{id}/region-subscriptions [post]
func (h *ociConfigHandler) subscribeRegion(c *gin.Context) {
	id, ok := pathID(c)
	if !ok {
		return
	}
	var req subscribeRegionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	subs, err := h.svc.SubscribeRegion(c.Request.Context(), id, req.RegionKey)
	if err != nil {
		respondError(c, err)
		return
	}
	c.JSON(http.StatusOK, subs)
}

// @Summary  服务限额查询
// @Tags     租户配置
// @Param    id path int true "配置 ID"
// @Success  200 {array} oci.LimitValue
// @Security BearerAuth
// @Router   /api/v1/oci-configs/{id}/limits [get]
func (h *ociConfigHandler) limits(c *gin.Context) {
	id, ok := pathID(c)
	if !ok {
		return
	}
	scopeType := strings.ToUpper(c.Query("scopeType"))
	if scopeType != "" && scopeType != "GLOBAL" && scopeType != "REGION" && scopeType != "AD" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "scopeType must be GLOBAL / REGION / AD"})
		return
	}
	q := oci.LimitsQuery{
		Region:             c.Query("region"),
		Service:            c.DefaultQuery("service", "compute"),
		Name:               c.Query("name"),
		ScopeType:          scopeType,
		AvailabilityDomain: c.Query("availabilityDomain"),
		NonZero:            c.Query("nonZero") == "true",
		WithAvailability:   c.Query("withAvailability") == "true",
	}
	values, err := h.svc.Limits(c.Request.Context(), id, q)
	if err != nil {
		respondError(c, err)
		return
	}
	c.JSON(http.StatusOK, values)
}
