package main

import (
	"context"
	"fmt"
	"time"

	"github.com/spf13/cobra"

	"git.jabali-panel.com/shukivaknin/jabali2/panel-api/internal/repository"
)

// newMalwarePurgeCmd implements `jabali malware-purge` — the cobra
// subcommand the M33 retention timer fires daily. Reads
// malware_settings.quarantine_retain_days, then hard-deletes
// malware_quarantine rows older than the cutoff that are already in
// a terminal state (deleted_at OR restored_at not null).
//
// Active rows older than retention are kept on purpose — operator
// must explicitly Restore or Delete via the UI before automatic
// purge applies. Never silently lose evidence.
func newMalwarePurgeCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "malware-purge",
		Short: "Hard-delete terminated malware quarantine rows past retention (M33)",
		Long: `Reads malware_settings.quarantine_retain_days and removes rows
in malware_quarantine whose detected_at is older than that cutoff
AND whose deleted_at OR restored_at is set (terminal state).

Active quarantined rows older than retention are kept — operator
must Restore or Delete them in the UI before the purge applies.

Wired into systemd timer jabali-malware-quarantine-purge.timer
(daily 04:00) by install_malware_stack in install.sh.`,
		RunE: func(cmd *cobra.Command, _ []string) error {
			ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
			defer cancel()
			if err := initConfig(); err != nil {
				return err
			}
			if err := initDB(); err != nil {
				return err
			}
			settings := repository.NewMalwareSettingsRepository(sharedDB)
			quarantine := repository.NewMalwareQuarantineRepository(sharedDB)
			if err := settings.EnsureDefault(ctx); err != nil {
				return fmt.Errorf("ensure default settings: %w", err)
			}
			s, err := settings.Get(ctx)
			if err != nil {
				return fmt.Errorf("get settings: %w", err)
			}
			cutoff := time.Now().UTC().Add(-time.Duration(s.QuarantineRetainDays) * 24 * time.Hour)
			n, err := quarantine.PurgeOlderThan(ctx, cutoff)
			if err != nil {
				return fmt.Errorf("purge: %w", err)
			}
			fmt.Fprintf(cmd.OutOrStdout(), "purged %d quarantine rows older than %s (retain_days=%d)\n",
				n, cutoff.Format(time.RFC3339), s.QuarantineRetainDays)
			return nil
		},
	}
	return cmd
}
