package jobdef

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

	"scheduler-backend/internal/urlrewrite"
)

type URLRewriteHandler struct{}

func (URLRewriteHandler) Key() string {
	return "url-rewrite"
}

func (URLRewriteHandler) Name() string {
	return "URL Rewrite"
}

func (URLRewriteHandler) Description() string {
	return "Batch-rewrite URL prefixes in MongoDB (user avatars, message media, favorites). Supports dry-run, apply, rollback, and cache invalidation."
}

func (URLRewriteHandler) Run(ctx context.Context, runtime Runtime, req ExecuteRequest) error {
	var params urlrewrite.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)
	}

	redisCfg := urlrewrite.RedisConfig{
		Addr:     runtime.Config.RedisAddr,
		Username: runtime.Config.RedisUsername,
		Password: runtime.Config.RedisPassword,
		Client:   runtime.Redis,
	}
	batchID, err := urlrewrite.Run(ctx, runtime.BusinessDB, params, redisCfg, logf)
	if err != nil {
		logf("url-rewrite failed: %v", err)
		return fmt.Errorf("url-rewrite %s failed (batch_id=%s): %w", params.Mode, batchID, err)
	}

	logf("url-rewrite finished, mode=%s batch_id=%s", params.Mode, batchID)
	return nil
}
