package tasks

import (
	"context"
	"time"

	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/service/ipanonymization"
)

// IPAnonymizationTask implements scheduler.Task for IP address anonymization
type IPAnonymizationTask struct {
	service ipanonymization.AnonymizeOldIPsService
	config  *config.Config
	logger  *zap.Logger
}

// ProvideIPAnonymizationTask creates a new IP anonymization task for Wire DI
func ProvideIPAnonymizationTask(
	service ipanonymization.AnonymizeOldIPsService,
	cfg *config.Config,
	logger *zap.Logger,
) *IPAnonymizationTask {
	return &IPAnonymizationTask{
		service: service,
		config:  cfg,
		logger:  logger.Named("IPAnonymizationTask"),
	}
}

// Name returns the task name
func (t *IPAnonymizationTask) Name() string {
	return "IP Anonymization"
}

// Schedule returns the cron schedule for this task
func (t *IPAnonymizationTask) Schedule() string {
	return t.config.Security.IPAnonymizationSchedule
}

// Execute runs the IP anonymization process
func (t *IPAnonymizationTask) Execute(ctx context.Context) error {
	if !t.config.Security.IPAnonymizationEnabled {
		t.logger.Debug("IP anonymization is disabled")
		return nil
	}

	startTime := time.Now()
	t.logger.Info("Starting IP anonymization task")

	// Run the anonymization process via the service
	if err := t.service.Execute(ctx); err != nil {
		t.logger.Error("IP anonymization task failed",
			zap.Error(err),
			zap.Duration("duration", time.Since(startTime)))
		return err
	}

	t.logger.Info("IP anonymization task completed successfully",
		zap.Duration("duration", time.Since(startTime)))

	return nil
}
