package handlers

import (
	"bytes"
	"image"
	"image/png"
	"mime/multipart"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strconv"
	"testing"

	"github.com/gin-gonic/gin"
	"wa-assistant/backend/models"
)

func productImageRequest(id uint, remove bool, imageData []byte) (*gin.Context, *httptest.ResponseRecorder) {
	var body bytes.Buffer
	form := multipart.NewWriter(&body)
	form.WriteField("name", "Gambar uji")
	if remove {
		form.WriteField("remove_image", "true")
	}
	if imageData != nil {
		f, _ := form.CreateFormFile("image", "sample.png")
		f.Write(imageData)
	}
	form.Close()
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)
	c.Request = httptest.NewRequest("PUT", "/", &body)
	c.Request.Header.Set("Content-Type", form.FormDataContentType())
	c.Params = gin.Params{{Key: "id", Value: "1"}, {Key: "pid", Value: strconv.Itoa(int(id))}}
	c.Set("tenant_id", uint(1))
	c.Set("user_id", uint(7))
	c.Set("role", "admin")
	return c, w
}

func TestProductImageRemovalAndReplacementAreAtomic(t *testing.T) {
	db, p, _ := naturalCheckoutTestDB(t)
	old := filepath.Join(t.TempDir(), "old.png")
	os.WriteFile(old, []byte("existing image"), 0600)
	db.Model(&p).Updates(map[string]any{"image_path": old, "image_mime": "image/png"})
	c, w := productImageRequest(p.ID, true, []byte("this is not an image"))
	UpdateProduct(c)
	if w.Code != 400 {
		t.Fatal(w.Code, w.Body.String())
	}
	db.First(&p, p.ID)
	if p.ImagePath != old {
		t.Fatal("failed replacement removed image reference")
	}
	if _, err := os.Stat(old); err != nil {
		t.Fatal("failed replacement deleted old file")
	}
	var data bytes.Buffer
	png.Encode(&data, image.NewRGBA(image.Rect(0, 0, 2, 2)))
	c, w = productImageRequest(p.ID, false, data.Bytes())
	UpdateProduct(c)
	if w.Code != 200 {
		t.Fatal(w.Code, w.Body.String())
	}
	db.First(&p, p.ID)
	if p.ImagePath == old || p.ImagePath == "" {
		t.Fatal("image did not change")
	}
	if _, err := os.Stat(old); !os.IsNotExist(err) {
		t.Fatal("old file retained after successful replacement")
	}
	newPath := p.ImagePath
	t.Cleanup(func() { os.Remove(newPath) })
	c, w = productImageRequest(p.ID, true, nil)
	UpdateProduct(c)
	if w.Code != 200 {
		t.Fatal(w.Code, w.Body.String())
	}
	db.First(&p, p.ID)
	if p.ImagePath != "" || p.ImageMime != "" {
		t.Fatal("image removal not persisted")
	}
	if _, err := os.Stat(newPath); !os.IsNotExist(err) {
		t.Fatal("removed file still exists")
	}
	other := models.Product{AgentID: 2, Name: "Other account", ImagePath: newPath}
	db.Create(&other)
	c, w = productImageRequest(other.ID, true, nil)
	UpdateProduct(c)
	if w.Code != 404 {
		t.Fatal("cross-agent image update accepted", w.Code)
	}
}
