package integration

import (
	"context"
	"encoding/json"
	"testing"
	"time"

	"github.com/RyanCopley/skybridge/faas/internal/domain"
	"github.com/RyanCopley/skybridge/faas/internal/runtime/docker"
	"go.uber.org/zap"
)

func TestDockerRuntimeIntegration(t *testing.T) {
	// Create a logger for testing
	logger, err := zap.NewDevelopment()
	if err != nil {
		t.Fatalf("Failed to create logger: %v", err)
	}
	defer logger.Sync()

	// Create the Docker runtime
	runtime, err := docker.NewSimpleDockerRuntime(logger)
	if err != nil {
		t.Skipf("Skipping test - Docker not available: %v", err)
	}

	// Test health check
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if err := runtime.HealthCheck(ctx); err != nil {
		t.Errorf("Docker runtime health check failed: %v", err)
	}

	// Get runtime info
	info, err := runtime.GetInfo(ctx)
	if err != nil {
		t.Errorf("Failed to get runtime info: %v", err)
	} else {
		t.Logf("Runtime Info: Type=%s, Version=%s, Available=%t", info.Type, info.Version, info.Available)
	}

	// Test with a simple function (using alpine image)
	function := &domain.FunctionDefinition{
		Name:    "test-function",
		Image:   "alpine:latest",
		Timeout: domain.Duration{Duration: 30 * time.Second},
		Memory:  128, // 128MB
	}

	// Deploy the function (pull the image)
	t.Log("Deploying function...")
	if err := runtime.Deploy(ctx, function); err != nil {
		t.Errorf("Failed to deploy function: %v", err)
	}

	// Test execution with a simple command
	input := json.RawMessage(`{"cmd": "echo Hello World"}`)

	t.Log("Executing function...")
	result, err := runtime.Execute(ctx, function, input)
	if err != nil {
		t.Errorf("Failed to execute function: %v", err)
	} else {
		t.Logf("Execution result: Duration=%v, Error=%s", result.Duration, result.Error)
		t.Logf("Output: %s", string(result.Output))
		t.Logf("Logs: %v", result.Logs)
	}
}

func TestHelloWorldFunction(t *testing.T) {
	// This test would require the hello-world-function image to be built
	// For now, we'll skip it
	t.Skip("Skipping hello world function test - requires custom image")
}
