package clustergateway

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/go-resty/resty/v2"
	"github.com/tidbcloud/cluster-service-ng/domain/entity"
)

type dmSourceListResponse struct {
	Total int        `json:"total"`
	Data  []dmSource `json:"data"`
}

type dmSource struct {
	SourceName string `json:"source_name"`
	Enable     bool   `json:"enable"`
}

func (c *clusterGatewayImpl) ListActiveDMSourceCount(
	ctx context.Context,
	sharedPool *entity.SharedPool,
	dmClusterID string,
) (int, error) {
	resp, err := c.callClusterProxy(ctx, sharedPool, http.MethodGet, operationMap["ListDMSources"], func(req *resty.Request) *resty.Request {
		return req.
			SetPathParam(sharedPoolIdParameter, sharedPool.GetId()).
			SetPathParam(dmClusterIdParameter, dmClusterID)
	})
	if err != nil {
		return 0, fmt.Errorf("list DM sources: %w", err)
	}
	if resp.StatusCode() < http.StatusOK || resp.StatusCode() >= http.StatusMultipleChoices {
		return 0, fmt.Errorf("list DM sources returned status %d: %s", resp.StatusCode(), resp.Body())
	}

	var sourceList dmSourceListResponse
	if err := json.Unmarshal(resp.Body(), &sourceList); err != nil {
		return 0, fmt.Errorf("decode DM source list response: %w", err)
	}

	activeCount := 0
	for _, source := range sourceList.Data {
		if source.Enable {
			activeCount++
		}
	}
	return activeCount, nil
}
