package encryptionkey

import (
	globalcommonv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/common/v1"
	"github.com/tidbcloud/tidb-management-service/nextgen-global-service/domain/entity"
	"github.com/tidbcloud/tidb-management-service/nextgen-global-service/infra/repoimpl/schema"
	"github.com/tidbcloud/tidb-management-service/utilities/bizerr"
	"github.com/tidbcloud/tidb-management-service/utilities/enum"
)

func modelToEntity(m *schema.EncryptionKey) (*entity.EncryptionKey, bizerr.BizError) {
	if m == nil {
		return nil, bizerr.New(bizerr.GeneralInternalErrorCode, "encryption key model is nil")
	}

	// Resolve service plan: prefer the encryption key's own value, fall back to
	// the joined Region's service plan for older records that have an empty column.
	servicePlanStr := m.ServicePlan
	if servicePlanStr == "" && m.Region != nil {
		servicePlanStr = m.Region.ServicePlan
	}

	en := &entity.EncryptionKey{
		Id:                 m.ID,
		TenantId:           m.TenantId,
		ServicePlan:        globalcommonv1.ServicePlan(globalcommonv1.ServicePlan_value[servicePlanStr]),
		ProviderIdentityId: m.ProviderIdentityId,
		CustomerManaged:    m.CustomerManaged,
		MasterKey:          m.MasterKey,
		InitialDataplaneId: m.InitialDataplaneId,
		ProviderId:         m.ProviderId,
		RegionId:           m.RegionId,
	}

	provider, err := enum.FromString[globalcommonv1.CloudProvider_Name](m.Provider.Name)
	if err != nil {
		return nil, bizerr.WrapError(err, "convert cloud provider")
	}
	en.ProviderName = globalcommonv1.CloudProvider_Name(provider)
	regionId, err := enum.RegionFromString(m.Provider.Name, m.Region.RegionName)
	if err != nil || regionId == globalcommonv1.Region_NAME_UNSPECIFIED {
		return nil, bizerr.WrapErrorWithCode(err, bizerr.ErrCodeParams, "invalid region: %s", m.Region.RegionName)
	}

	en.RegionName = regionId

	return en, nil
}

func entityToModel(e *entity.EncryptionKey) (*schema.EncryptionKey, bizerr.BizError) {
	if e == nil {
		return nil, bizerr.New(bizerr.GeneralInternalErrorCode, "encryption key entity is nil")
	}

	return &schema.EncryptionKey{
		ID:                 e.Id,
		TenantId:           e.TenantId,
		ProviderId:         e.ProviderId,
		RegionId:           e.RegionId,
		ProviderIdentityId: e.ProviderIdentityId,
		CustomerManaged:    e.CustomerManaged,
		ServicePlan:        e.ServicePlan.String(),
		MasterKey:          e.MasterKey,
		InitialDataplaneId: e.InitialDataplaneId,
	}, nil
}
