package api

import (
	"context"

	"github.com/tidbcloud/ticdc-service/pkg/clusterproxy/client"
)

const (
	pdGetSafePointPath = "/pd/pd/api/v1/gc/safepoint"
)

// Safepoint represents the safepoint of the PD server
type Safepoint struct {
	SP uint64 `json:"gc_safe_point"`
}

// PDClientGetter defines the interface for getting a PD client
type PDClientGetter interface {
	PDClient() PDClient
}

// PDClient defines the interface for PD operations
type PDClient interface {
	// GetPDSafepoint returns the safepoint of the PD server
	GetPDSafepoint(ctx context.Context) (*Safepoint, error)
}

type pdClient struct {
	client client.Client
}

// NewPdClient creates a new instance of the PDClient with the given client
func NewPdClient(client client.Client) PDClient {
	return &pdClient{
		client: client,
	}
}

func (p *pdClient) GetPDSafepoint(ctx context.Context) (*Safepoint, error) {
	ctx, span := Tracer.Start(ctx, "GetPDSafepoint")
	defer span.End()

	var safepoint Safepoint
	err := p.client.Request(ctx, "GET", pdGetSafePointPath, nil, &safepoint)
	if err != nil {
		return nil, err
	}
	return &safepoint, nil
}
