package repository

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

	"github.com/tidbcloud/serverless-metering/pkg/config"
)

type MetaClientClusterBranchRepo struct {
	metaServerHost string
	metaServerPort int
	client         http.Client
}

func NewMetaClientClusterBranchRepo() *MetaClientClusterBranchRepo {
	cfg := config.Global().Repo
	client := http.Client{
		Timeout: time.Second * 3,
	}
	return &MetaClientClusterBranchRepo{
		client:         client,
		metaServerHost: cfg.MetaServerHost,
		metaServerPort: cfg.MetaServerPort,
	}
}

func (r *MetaClientClusterBranchRepo) GetClusterBranchByPrimaryID(ctx context.Context, primaryID string) (*ClusterBranch, error) {
	return r.requestMetaService(ctx, "primary_id", primaryID)
}

func (r *MetaClientClusterBranchRepo) GetClusterBranchByKeyspaceID(ctx context.Context, keyspaceID string) (*ClusterBranch, error) {
	return r.requestMetaService(ctx, "keyspace_id", keyspaceID)
}

func (r *MetaClientClusterBranchRepo) requestMetaService(_ context.Context, key, value string) (*ClusterBranch, error) {
	url := fmt.Sprintf("http://%s:%d/api/v1/cluster-or-branch?%s=%s", r.metaServerHost, r.metaServerPort, key, value)
	resp, err := r.client.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("http response not ok, status: %d, body: %s", resp.StatusCode, string(data))
	}

	var clusterBranch ClusterBranch
	err = json.Unmarshal(data, &clusterBranch)
	if err != nil {
		return nil, err
	}
	return &clusterBranch, nil
}
