package ngoperation

import (
	"context"
	"fmt"

	commonv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/common/v1"
	nextgenv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/nextgen/v1"

	"github.com/tidbcloud/devops/pkg/infra/clients/coresvccli"
)

func isOriginalResourcePoolServicePlan(plan commonv1.ServicePlan) bool {
	switch plan {
	case commonv1.ServicePlan_Premium, commonv1.ServicePlan_BYOC:
		return true
	default:
		return false
	}
}

func isSetDefaultResourcePoolServicePlan(plan commonv1.ServicePlan) bool {
	switch plan {
	case commonv1.ServicePlan_Premium, commonv1.ServicePlan_BYOC, commonv1.ServicePlan_Essential_V2:
		return true
	default:
		return false
	}
}

func validateSetDefaultResourcePoolServicePlan(ctx context.Context, mgmt *coresvccli.MgmtService, resourcePoolID uint64, organizationID uint64, action string) error {
	rp, err := mgmt.GetResourcePool(ctx, resourcePoolID)
	if err != nil {
		return err
	}
	resourcePool := rp.GetResourcePool()
	servicePlan := resourcePool.GetServicePlan()
	if !isSetDefaultResourcePoolServicePlan(servicePlan) {
		return fmt.Errorf("service plan %s is not supported for %s", servicePlan.String(), action)
	}

	if servicePlan == commonv1.ServicePlan_Essential_V2 {
		return nil
	}

	if organizationID == 0 {
		return fmt.Errorf("service plan %s does not support organization_id 0 for %s", servicePlan.String(), action)
	}
	if resourcePool.GetOwnerType() != nextgenv1.ResourcePool_ORGANIZATION {
		return fmt.Errorf("resource pool owner type %s is not supported for %s", resourcePool.GetOwnerType().String(), action)
	}
	if resourcePool.GetOwnerId() != organizationID {
		return fmt.Errorf("organization_id %d does not match resource pool owner %d for %s", organizationID, resourcePool.GetOwnerId(), action)
	}
	return nil
}
