package jobs

import (
	"context"
	"os"
	"time"

	. "github.com/riverqueue/river"
	log "github.com/sirupsen/logrus"
	_ "go.ipao.vip/atom"
	"go.ipao.vip/atom/contracts"
)

var _ contracts.JobArgs = (*RemoveFile)(nil)

type RemoveFile struct {
	FilePath string `json:"file_path"`
}

func (s RemoveFile) InsertOpts() InsertOpts {
	return InsertOpts{
		Queue:    QueueDefault,
		Priority: PriorityDefault,
		// ScheduledAt: time.Now().Add(time.Minute * 10),
	}
}

func (s RemoveFile) Kind() string     { return "remove_file" }
func (a RemoveFile) UniqueID() string { return a.Kind() }

var _ Worker[RemoveFile] = (*RemoveFileWorker)(nil)

// @provider(job)
type RemoveFileWorker struct {
	WorkerDefaults[RemoveFile]
}

func (w *RemoveFileWorker) NextRetry(job *Job[RemoveFile]) time.Time {
	return time.Now().Add(30 * time.Second)
}

func (w *RemoveFileWorker) Work(ctx context.Context, job *Job[RemoveFile]) error {
	log := log.WithField("job", job.Args.Kind())

	log.Infof("[Start] Working on job with strings: %+v", job.Args)
	defer log.Infof("[End] Finished %s", job.Args.Kind())

	// Check if the file exists
	if _, err := os.Stat(job.Args.FilePath); os.IsNotExist(err) {
		log.Warn("File does not exist: %v", job.Args.FilePath)
		return nil
	}
	// Remove the file
	if err := os.Remove(job.Args.FilePath); err != nil {
		log.Errorf("Error removing file: %v", err)
		return err
	}
	log.Infof("File removed successfully: %v", job.Args.FilePath)

	return nil
}
