package extension

import (
	"context"
	"os"
	"path/filepath"

	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DownloadExtensionZipLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDownloadExtensionZipLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DownloadExtensionZipLogic {
	return &DownloadExtensionZipLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}

// DownloadExtensionZip — ST-16: return path for handler to stream (logic only validates)
func (l *DownloadExtensionZipLogic) DownloadExtensionZip() (*types.Empty, error) {
	path := l.svcCtx.ExtensionZipPath
	if path == "" {
		return nil, response.Biz(404, 404010, "extension zip not found")
	}
	st, err := os.Stat(path)
	if err != nil || st.Size() == 0 {
		return nil, response.Biz(404, 404010, "extension zip not found")
	}
	return &types.Empty{}, nil
}

// ResolveZipPath used by custom handler
func ResolveZipPath(svcCtx *svc.ServiceContext) string {
	if svcCtx.ExtensionZipPath != "" {
		return svcCtx.ExtensionZipPath
	}
	// try common locations relative to cwd
	cands := []string{
		"../../web/public/downloads/haixun-threads-sync.zip",
		"../web/public/downloads/haixun-threads-sync.zip",
		"apps/web/public/downloads/haixun-threads-sync.zip",
	}
	for _, c := range cands {
		if st, err := os.Stat(c); err == nil && st.Size() > 0 {
			return filepath.Clean(c)
		}
	}
	return ""
}
