package service

import (
	"context"
	"fmt"

	"github.com/KscSDK/ksc-sdk-go/ksc"
	"github.com/KscSDK/ksc-sdk-go/ksc/utils"
	"github.com/KscSDK/ksc-sdk-go/service/billunion"
	"github.com/spf13/viper"
	"go.uber.org/zap"

	"github.com/pingcap-inc/data-ingestion-tools/internal/itcronjob/store"
	"github.com/pingcap-inc/data-ingestion-tools/model"
	"github.com/pingcap-inc/data-ingestion-tools/pkg/log"
)

type KsSrv interface {
	FetchKsBill(ctx context.Context, monthNow string) ([]model.BillingRecord, error)
}

type ksService struct {
	store store.Factory
}

var _ KsSrv = (*ksService)(nil)

func newKs(str *service) *ksService {
	return &ksService{store: str.store}
}

func (k *ksService) FetchKsBill(ctx context.Context, monthNow string) ([]model.BillingRecord, error) {
	ak := viper.GetString("kscloud.ak")
	sk := viper.GetString("kscloud.sk")
	region := "cn-beijing-6"
	svc := billunion.SdkNew(ksc.NewClient(ak, sk), &ksc.Config{Region: &region},
		&utils.UrlInfo{
			UseSSL: true,
		})

	input := map[string]interface{}{
		"BillBeginMonth": monthNow,
		"BillEndMonth":   monthNow,
	}
	result, err := svc.DescribeBillSummaryByProject(&input)
	if err != nil {
		log.L(ctx).Error("fetch ks bill failed", zap.Error(err))

		return nil, err
	}

	var records []model.BillingRecord
	resMap := *result
	v, ok := resMap["SummaryOverview"]
	if !ok {
		return nil, fmt.Errorf("no SummaryOverview in response")
	}

	for _, item := range v.([]interface{}) {
		it, o1 := item.(map[string]interface{})
		if !o1 {
			return nil, fmt.Errorf("item is not map[string]interface{}")
		}
		projName, o2 := it["ProjectName"].(string)
		cost, o3 := it["RealTotalCost"].(string)
		if !o2 || !o3 {
			return nil, fmt.Errorf("no ProjectName or RealTotalCost in item")
		}
		record := model.BillingRecord{
			ProjName: projName,
			Cost:     cost,
		}

		records = append(records, record)
	}

	return records, nil
}
