package extension

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

	"apps/backend/internal/logic/extension"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
)

func DownloadExtensionZipHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		l := extension.NewDownloadExtensionZipLogic(r.Context(), svcCtx)
		if _, err := l.DownloadExtensionZip(); err != nil {
			response.Write(r.Context(), w, nil, err)
			return
		}
		path := svcCtx.ExtensionZipPath
		if path == "" {
			path = extension.ResolveZipPath(svcCtx)
		}
		w.Header().Set("Content-Type", "application/zip")
		w.Header().Set("Content-Disposition", `attachment; filename="haixun-threads-sync.zip"`)
		http.ServeFile(w, r, filepath.Clean(path))
	}
}

// ensure zip exists for tests
func zipExists(p string) bool {
	st, err := os.Stat(p)
	return err == nil && st.Size() > 0
}
