package repoter

import (
	"fmt"
	"io"
	"os"
	"testing"

	"github.com/tidbcloud/metering/pkg/common/models"
	"github.com/tidbcloud/metering/pkg/common/utils"
)

func TestMain(m *testing.M) {
	path := setup()
	code := m.Run()
	cleanup(path)
	os.Exit(code)
}

func setup() string {
	// prepare sqlite
	abspath, err := utils.EnsureCache("cachetest", repotercachepath)
	if err != nil {
		panic(err)
	}
	db, err := ensureSQLite(abspath + "/20240812.db")
	if err != nil {
		panic(err)
	}
	db.AutoMigrate(&models.BillingReport{})
	r := &models.BillingReport{
		TenantID:      123,
		CostID:        utils.GenerateID(),
		Cost:          100000000,
		CostTimestamp: 1723487507,
		Labels:        `{"project":"123","cluster":"123"}`,
		Unit:          "network-traffic:azure:eastus:cross_region",
	}
	db.Create(r)
	return abspath
}

func cleanup(path string) {
	err := os.RemoveAll(path)
	if err != nil {
		panic(err)
	}

}

func copyFile(src, dst string) error {
	sourceFile, err := os.Open(src)
	if err != nil {
		return fmt.Errorf("open failed: %v", err)
	}
	defer sourceFile.Close()

	destinationFile, err := os.Create(dst)
	if err != nil {
		return fmt.Errorf("create failed: %v", err)
	}
	defer destinationFile.Close()

	// copy file
	_, err = io.Copy(destinationFile, sourceFile)
	if err != nil {
		return fmt.Errorf("copy failed: %v", err)
	}

	// ensure data is written to disk
	err = destinationFile.Sync()
	if err != nil {
		return fmt.Errorf("sync failed: %v", err)
	}

	return nil
}
