package httpapi

import (
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/config"
)

func TestServeGeneratedStaticAsset(t *testing.T) {
	storageDir := t.TempDir()
	if err := os.WriteFile(filepath.Join(storageDir, "result.png"), []byte("png"), 0o644); err != nil {
		t.Fatalf("failed to write generated asset fixture: %v", err)
	}
	server := &Server{cfg: config.Config{LocalGeneratedStorageDir: storageDir}}
	request := httptest.NewRequest(http.MethodGet, "/static/generated/result.png", nil)
	request.SetPathValue("asset", "result.png")
	response := httptest.NewRecorder()

	server.serveGeneratedStaticAsset(response, request)

	if response.Code != http.StatusOK {
		t.Fatalf("expected generated asset to be served, got status %d", response.Code)
	}
	if response.Body.String() != "png" {
		t.Fatalf("unexpected generated asset payload: %q", response.Body.String())
	}
}

func TestServeUploadedStaticAsset(t *testing.T) {
	storageDir := t.TempDir()
	if err := os.WriteFile(filepath.Join(storageDir, "upload.pdf"), []byte("pdf"), 0o644); err != nil {
		t.Fatalf("failed to write uploaded asset fixture: %v", err)
	}
	server := &Server{cfg: config.Config{LocalUploadedStorageDir: storageDir}}
	request := httptest.NewRequest(http.MethodGet, "/static/uploaded/upload.pdf", nil)
	request.SetPathValue("asset", "upload.pdf")
	response := httptest.NewRecorder()

	server.serveUploadedStaticAsset(response, request)

	if response.Code != http.StatusOK {
		t.Fatalf("expected uploaded asset to be served, got status %d", response.Code)
	}
	if response.Body.String() != "pdf" {
		t.Fatalf("unexpected uploaded asset payload: %q", response.Body.String())
	}
}

func TestServeLocalStaticAssetRejectsTraversal(t *testing.T) {
	storageDir := t.TempDir()
	server := &Server{cfg: config.Config{LocalGeneratedStorageDir: storageDir}}
	request := httptest.NewRequest(http.MethodGet, "/static/generated/..", nil)
	request.SetPathValue("asset", "..")
	response := httptest.NewRecorder()

	server.serveGeneratedStaticAsset(response, request)

	if response.Code != http.StatusNotFound {
		t.Fatalf("expected traversal-like generated asset name to 404, got status %d", response.Code)
	}
}
