package dbutil

// Database access should be done through this file.
import (
	"github.com/pingcap/dbaas/central/db/entity"
	"github.com/pingcap/errcode"
	"github.com/pingcap/errors"
	"gorm.io/gorm"
)

func ConvertRestoreTracking(restore *entity.Restore) *entity.RestoreTracking {
	return &entity.RestoreTracking{
		RestoreID:   restore.ID,
		Status:      restore.Status,
		Description: "",
	}
}

func RestoresFetchAll(tx *gorm.DB, clusterID entity.ID) ([]entity.Restore, error) {
	var restores []entity.Restore
	err := entity.NewRestoreQuerySet(tx).ClusterIDEq(clusterID).All(&restores)
	return restores, err
}

func RestoresInProgress(tx *gorm.DB, clusterID entity.ID) ([]entity.Restore, error) {
	var restores []entity.Restore
	err := entity.NewRestoreQuerySet(tx).ClusterIDEq(clusterID).StatusNe(entity.RestoreStatus_SUCCESS).All(&restores)
	return restores, err
}

// GetRestoreByClusterID is get the restore by clsuterID
func GetRestoreByClusterID(tx *gorm.DB, orgID, clusterID entity.ID) (*entity.Restore, error) {
	var restore entity.Restore
	err := entity.NewRestoreQuerySet(tx).PreloadCluster().ClusterIDEq(clusterID).One(&restore)
	if err != nil {
		return &restore, errors.Annotate(TagNotFound(err), "GetRestoreByClusterID")
	}
	if restore.Cluster.TenantID != orgID {
		return &restore, errcode.NewForbiddenErr(errors.New("you do not have permission to access this resource"))
	}
	if restore.ClusterID != clusterID {
		return &restore, errors.Errorf("cluster %d does not have restore", clusterID)
	}
	return &restore, nil
}
