package jobqueue

import (
	"context"
	"io/ioutil"
	"os"
	"path"
	"testing"
)

func TestFileOperationRunnable(t *testing.T) {

	dir := t.TempDir()
	err := os.Chdir(dir)
	if err != nil {
		t.Fatalf("Failed to change directory: %v", err)
	}

	ctx := context.Background()

	testFilePath := path.Join(dir, "test.txt")
	testContent := "Hello, World!"

	// Test FileOperationCreate
	createRunner := FileOperationRunnable{Operation: FileOperationCreate, FilePath: testFilePath}
	_, err = createRunner.Run(ctx)
	if err != nil {
		t.Fatalf("Failed to create file: %v", err)
	}

	// Test FileOperationWrite
	writeRunner := FileOperationRunnable{Operation: FileOperationWrite, FilePath: testFilePath, Content: testContent}
	_, err = writeRunner.Run(ctx)
	if err != nil {
		t.Fatalf("Failed to write to file: %v", err)
	}

	// Test FileOperationRead
	readRunner := FileOperationRunnable{Operation: FileOperationRead, FilePath: testFilePath}
	result, err := readRunner.Run(ctx)
	if err != nil || result.Data.Content != testContent {
		t.Fatalf("Failed to read from file: %v", err)
	}

	// Test FileOperationAppend
	appendContent := " Appended."
	appendRunner := FileOperationRunnable{Operation: FileOperationAppend, FilePath: testFilePath, Content: appendContent}
	_, err = appendRunner.Run(ctx)
	if err != nil {
		t.Fatalf("Failed to append to file: %v", err)
	}

	// Re-verify content after append
	updatedContent, _ := ioutil.ReadFile(testFilePath)
	if string(updatedContent) != testContent+appendContent {
		t.Fatalf("Append operation failed.")
	}

	// Test FileOperationDelete
	deleteRunner := FileOperationRunnable{Operation: FileOperationDelete, FilePath: testFilePath}
	_, err = deleteRunner.Run(ctx)
	if err != nil {
		t.Fatalf("Failed to delete file: %v", err)
	}

	// Verify the file is deleted
	if _, err := os.Stat(testFilePath); !os.IsNotExist(err) {
		t.Fatalf("File deletion failed.")
	}
}