package tidbtools

import ccapi "github.com/tidbcloud/devops/api/cloudconfig"

// ListChangefeedsResp is the response body for `GET .../changefeeds`.
// It reuses ChangefeedSummary defined in overview.go.
//
// Note: the unified changefeed response does not expose a dataset-wide total;
// `Total` here is the size of the returned slice
// (i.e. equal to len(Items)). The Tools-page list is non-paginated, so
// this is acceptable for now — see design doc §5.2.
type ListChangefeedsResp struct {
	Items []*ChangefeedSummary `json:"items"`
	Total int64                `json:"total"`
}

// toChangefeedSummaries projects the unified changefeed list into the
// FE-facing summary slice. Returns an empty (non-nil) slice when pb is
// nil or contains no changefeeds.
func toChangefeedSummaries(resp *ccapi.ListInternalChangefeedsResp) []*ChangefeedSummary {
	if resp == nil {
		return []*ChangefeedSummary{}
	}
	items := make([]*ChangefeedSummary, 0, len(resp.Changefeeds))
	for _, cf := range resp.Changefeeds {
		if cf == nil {
			continue
		}
		items = append(items, &ChangefeedSummary{
			ID:          cf.Id,
			DisplayName: cf.DisplayName,
			Status:      ChangefeedStatus(cf.Status),
		})
	}
	return items
}

// ToListChangefeedsResp converts a unified changefeed list to the FE-facing
// ListChangefeedsResp.
func ToListChangefeedsResp(resp *ccapi.ListInternalChangefeedsResp) *ListChangefeedsResp {
	items := toChangefeedSummaries(resp)
	return &ListChangefeedsResp{
		Items: items,
		Total: int64(len(items)),
	}
}

// ToListChangefeedsOverviewResp converts a unified changefeed list to the
// FE-facing ListChangefeedsOverviewResp used by the overview panel.
func ToListChangefeedsOverviewResp(resp *ccapi.ListInternalChangefeedsResp) *ListChangefeedsOverviewResp {
	items := toChangefeedSummaries(resp)
	return &ListChangefeedsOverviewResp{
		Items: items,
		Total: int64(len(items)),
	}
}
