package deltalake

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

	"github.com/tidbcloud/observability/cmd/diagnosis-compute/pkg/config"
	"github.com/tidbcloud/observability/cmd/diagnosis-compute/pkg/types"
)

func Sync2Deltalake(ctx context.Context, bucket string, s3key string, info types.ClusterInfo) error {
	if testing.Testing() || config.Spec || (config.Vendor != "aws" && config.Vendor != "gcp" && config.Vendor != "azure" && config.Vendor != "alicloud") {
		return nil
	}
	requestBody := types.LogStats2DeltalakeRequest{
		Vendor:  config.Vendor,
		Org:     info.TenantID,
		Project: info.ProjectID,
		Cluster: info.ClusterID,
		Bucket:  bucket,
	}

	switch config.Vendor {
	case "aws", "alicloud":
		requestBody.SqliteS3Path = fmt.Sprintf("s3://%s/%s", bucket, s3key)
	case "gcp":
		requestBody.SqliteS3Path = fmt.Sprintf("gs://%s/%s", bucket, s3key)
	case "azure":
		requestBody.SqliteS3Path = fmt.Sprintf("az://%s/%s", bucket, s3key)
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", "http://deltalake-ops-server-service:8080/deltalake/log_stats", bytes.NewBuffer(jsonData))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusAccepted {
		return fmt.Errorf("resp.StatusCode is %d", resp.StatusCode)
	}
	return nil
}
