package br

import (
	"context"
	"fmt"

	"github.com/tidbcloud/cluster-service-ng/pkg/storage/mysql/schema"
	"github.com/tidbcloud/cluster-service-ng/pkg/storage/repo"
)

func hasOtherActiveRestoreWithSameBucketPermissionForLW(
	ctx context.Context,
	restoreID string,
	lwRestoreRepo repo.LightweightRestoreRepo,
	manualRestoreRepo repo.ManualBackupRestoreRepo,
) (bool, error) {
	restore, err := lwRestoreRepo.Load(ctx, restoreID, false)
	if err != nil {
		return false, fmt.Errorf("failed to load lw restore: %w", err)
	}
	return hasOtherActiveRestoreWithSameBucketPermission(
		ctx,
		restore.SourceSharedPoolID,
		restore.TargetSharedPoolID,
		[]string{restoreID},
		nil,
		lwRestoreRepo,
		manualRestoreRepo,
	)
}

func hasOtherActiveRestoreWithSameBucketPermissionForManual(
	ctx context.Context,
	restoreID string,
	lwRestoreRepo repo.LightweightRestoreRepo,
	manualRestoreRepo repo.ManualBackupRestoreRepo,
) (bool, error) {
	restore, err := manualRestoreRepo.Load(ctx, restoreID, false)
	if err != nil {
		return false, fmt.Errorf("failed to load manual backup restore: %w", err)
	}
	return hasOtherActiveRestoreWithSameBucketPermission(
		ctx,
		restore.SourceSharedPoolID,
		restore.TargetSharedPoolID,
		nil,
		[]string{restoreID},
		lwRestoreRepo,
		manualRestoreRepo,
	)
}

func hasOtherActiveRestoreWithSameBucketPermission(
	ctx context.Context,
	sourceSharedPoolID string,
	targetSharedPoolID string,
	excludeLWRestoreIDs []string,
	excludeManualRestoreIDs []string,
	lwRestoreRepo repo.LightweightRestoreRepo,
	manualRestoreRepo repo.ManualBackupRestoreRepo,
) (bool, error) {
	lwRestores, err := lwRestoreRepo.List(ctx, &repo.LightweightRestoreFilter{
		ExcludeRestoreID:   excludeLWRestoreIDs,
		IncludeStatuses:    []string{schema.LightweightRestoreStatusRunning},
		SourceSharedPoolID: &sourceSharedPoolID,
		TargetSharedPoolID: &targetSharedPoolID,
		IncludeDeleted:     false,
	})
	if err != nil {
		return false, fmt.Errorf("failed to list other running lw restores: %w", err)
	}
	if len(lwRestores) > 0 {
		return true, nil
	}

	manualRestores, err := manualRestoreRepo.List(ctx, &repo.ManualBackupRestoreFilter{
		ExcludeRestoreID:   excludeManualRestoreIDs,
		IncludeStatuses:    []string{schema.ManualBackupRestoreStatusRunning},
		SourceSharedPoolID: &sourceSharedPoolID,
		TargetSharedPoolID: &targetSharedPoolID,
		IncludeDeleted:     false,
	})
	if err != nil {
		return false, fmt.Errorf("failed to list other running manual backup restores: %w", err)
	}

	return len(manualRestores) > 0, nil
}
