package models

import (
	// nolint:gosec
	"crypto/md5"
	"encoding/hex"
	"strconv"
	"strings"

	"github.com/tidbcloud/observability/o11ymetering/pkg/common/constants"
	"gorm.io/gorm"
)

type MonthlyProportion struct {
	ID        string `gorm:"primaryKey;size:32"`
	Timestamp int32  `gorm:"size:32;comment:''"`
	Month     int32  `gorm:"size:32;comment:''"`
	Region    string `gorm:"not null;size:32"`

	Env           constants.BizEnv        `gorm:"size:16;comment:''"`
	MeteringGroup constants.MeteringGroup `gorm:"not null;size:32;comment:''"`
	Tenant        string                  `gorm:"size:32;comment:''"`

	CloudService constants.CloudService `gorm:"size:32;comment:''"`
	Proportion   float64                `gorm:"size:64;comment:''"`
}

func (t *MonthlyProportion) BeforeCreate(tx *gorm.DB) (err error) {
	if len(t.ID) == 0 {
		t.BuildID()
	}
	return nil
}

func (t *MonthlyProportion) BuildID() string {
	strs := []string{
		strconv.Itoa(int(t.Timestamp)),
		t.Region,
		string(t.CloudService),
		string(t.Env),
		string(t.MeteringGroup),
		t.Tenant,
	}
	text := strings.Join(strs, "-")
	// nolint:gosec
	hash := md5.Sum([]byte(text))
	t.ID = hex.EncodeToString(hash[:])
	return t.ID
}
