package jobdef

import (
	"context"
	"encoding/json"
	"fmt"

	"scheduler-backend/internal/s3migrate"
)

type S3MigrateHandler struct{}

func (S3MigrateHandler) Key() string {
	return "s3-migrate"
}

func (S3MigrateHandler) Name() string {
	return "S3 Migrate"
}

func (S3MigrateHandler) Description() string {
	return "Migrate objects between S3-compatible storage engines (MinIO, AWS S3, etc.). Streams files via presigned URLs and updates MongoDB engine records."
}

func (S3MigrateHandler) Run(ctx context.Context, runtime Runtime, req ExecuteRequest) error {
	var params s3migrate.Params
	if err := json.Unmarshal(req.Params, &params); err != nil {
		return fmt.Errorf("parse params: %w", err)
	}

	logf := func(msg string, args ...any) {
		line := fmt.Sprintf(msg, args...)
		req.LogCollector.Appendf("%s", line)
		runtime.Logger.Info(line, "jobID", req.JobID, "executionID", req.ExecutionID)
	}

	if err := s3migrate.Run(ctx, runtime.BusinessDB, params, logf); err != nil {
		logf("s3-migrate failed: %v", err)
		return fmt.Errorf("s3-migrate failed: %w", err)
	}

	logf("s3-migrate finished")
	return nil
}
