package api

import (
	"context"
	"fmt"

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

const (
	pdGetSafePointPath = "/proxy/cluster/%s/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",
		fmt.Sprintf(
			pdGetSafePointPath,
			p.client.GetTiDBGroup().GetSharedPoolId(),
		),
		nil, &safepoint)
	if err != nil {
		return nil, err
	}
	return &safepoint, nil
}
