package builder

import (
	"bytes"
	"mime/multipart"
	"net/textproto"
	"os"
	"path/filepath"
	"testing"
)

func TestSaveUploadedFusionPayloadCreatesPrepsDir(t *testing.T) {
	dataDir := t.TempDir()
	h := &Handler{dataDir: dataDir}

	body := &bytes.Buffer{}
	w := multipart.NewWriter(body)
	partHeader := make(textproto.MIMEHeader)
	partHeader.Set("Content-Type", "application/octet-stream")
	partHeader.Set("Content-Disposition", `form-data; name="prep_exe"; filename="prep.exe"`)
	part, err := w.CreatePart(partHeader)
	if err != nil {
		t.Fatal(err)
	}
	if _, err := part.Write([]byte("MZfake")); err != nil {
		t.Fatal(err)
	}
	w.Close()

	r := multipart.NewReader(body, w.Boundary())
	form, err := r.ReadForm(10 << 20)
	if err != nil {
		t.Fatal(err)
	}
	fileHeaders := form.File["prep_exe"]
	if len(fileHeaders) == 0 {
		t.Fatal("missing file header")
	}
	f, err := fileHeaders[0].Open()
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	path, cleanup, err := h.saveUploadedFusionPayload(f, fileHeaders[0])
	if err != nil {
		t.Fatal(err)
	}
	defer cleanup()

	if _, err := os.Stat(path); err != nil {
		t.Fatalf("payload not saved: %v", err)
	}
	if _, err := os.Stat(filepath.Join(dataDir, "preps")); err != nil {
		t.Fatalf("preps dir not created: %v", err)
	}
}

// Fusion now accepts any file with an extension (.txt, .pdf, .mp4, .docx, etc.)
// Only files with no extension at all are rejected.
func TestSaveUploadedFusionPayloadAcceptsAnyExtension(t *testing.T) {
	for _, fname := range []string{"report.pdf", "clip.mp4", "doc.docx", "data.txt", "archive.zip"} {
		h := &Handler{dataDir: t.TempDir()}
		body := &bytes.Buffer{}
		w := multipart.NewWriter(body)
		partHeader := make(textproto.MIMEHeader)
		partHeader.Set("Content-Disposition", `form-data; name="prep_exe"; filename="`+fname+`"`)
		part, _ := w.CreatePart(partHeader)
		_, _ = part.Write([]byte("x"))
		w.Close()
		r := multipart.NewReader(body, w.Boundary())
		form, _ := r.ReadForm(10 << 20)
		f, _ := form.File["prep_exe"][0].Open()
		_, cleanup, err := h.saveUploadedFusionPayload(f, form.File["prep_exe"][0])
		f.Close()
		if err != nil {
			t.Errorf("expected %s to be accepted, got error: %v", fname, err)
		} else {
			cleanup()
		}
	}
}

func TestSaveUploadedFusionPayloadRejectsNoExtension(t *testing.T) {
	h := &Handler{dataDir: t.TempDir()}
	body := &bytes.Buffer{}
	w := multipart.NewWriter(body)
	partHeader := make(textproto.MIMEHeader)
	partHeader.Set("Content-Disposition", `form-data; name="prep_exe"; filename="noextension"`)
	part, _ := w.CreatePart(partHeader)
	_, _ = part.Write([]byte("x"))
	w.Close()
	r := multipart.NewReader(body, w.Boundary())
	form, _ := r.ReadForm(10 << 20)
	f, _ := form.File["prep_exe"][0].Open()
	defer f.Close()
	_, _, err := h.saveUploadedFusionPayload(f, form.File["prep_exe"][0])
	if err == nil {
		t.Fatal("expected error for file with no extension")
	}
}
