package action

import (
	"context"
	"fmt"
	"strconv"

	"github.com/tidbcloud/fastflow/pkg/entity/run"

	"github.com/tidbcloud/tidb-management-service/tidb-mgmt-service/domain/constant"
	"github.com/tidbcloud/tidb-management-service/tidb-mgmt-service/domain/entity"
	"github.com/tidbcloud/tidb-management-service/tidb-mgmt-service/domain/repository"
)

// loadProjectMigrationTaskFromCtx reads the task ID from the workflow execution
// context vars and returns the corresponding ProjectMigrationTask.
func loadProjectMigrationTaskFromCtx(ctx run.ExecuteContext, repo repository.ProjectMigrationTaskRepo) (*entity.ProjectMigrationTask, error) {
	taskIDStr, ok := ctx.GetVar(constant.KeyProjectMigrationTaskID)
	if !ok {
		return nil, fmt.Errorf("var %q not found in workflow context", constant.KeyProjectMigrationTaskID)
	}
	taskID, err := strconv.ParseUint(taskIDStr, 10, 64)
	if err != nil {
		return nil, fmt.Errorf("parse task id %q: %w", taskIDStr, err)
	}
	return loadProjectMigrationTaskByIDCtx(ctx.Context(), repo, taskID)
}

// loadProjectMigrationTaskByIDCtx loads a ProjectMigrationTask by its primary key.
func loadProjectMigrationTaskByIDCtx(
	ctx context.Context,
	repo repository.ProjectMigrationTaskRepo,
	taskID uint64,
) (*entity.ProjectMigrationTask, error) {
	task, err := repo.GetByID(ctx, taskID)
	if err != nil {
		return nil, fmt.Errorf("get project migration task by id %d: %w", taskID, err)
	}
	if task == nil {
		return nil, fmt.Errorf("project migration task %d not found", taskID)
	}
	return task, nil
}
