package authorization

import (
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strconv"

	"tydata-server/app/main/api/internal/logic/authorization"
	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"
	"tydata-server/app/main/model"
	"tydata-server/common/result"
	"tydata-server/common/xerr"
	"tydata-server/pkg/lzkit/validator"

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

func DownloadAuthorizationDocumentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.DownloadAuthorizationDocumentReq
		if err := httpx.Parse(r, &req); err != nil {
			result.ParamErrorResult(r, w, err)
			return
		}
		if err := validator.Validate(req); err != nil {
			result.ParamValidateErrorResult(r, w, err)
			return
		}
		l := authorization.NewDownloadAuthorizationDocumentLogic(r.Context(), svcCtx)
		resp, err := l.DownloadAuthorizationDocument(&req)
		if err != nil {
			if errors.Is(err, model.ErrNotFound) {
				httpx.WriteJson(w, http.StatusNotFound, result.Error(xerr.CUSTOM_ERROR, "授权书不存在"))
				return
			}
			result.HttpResult(r, w, nil, err)
			return
		}

		file, openErr := os.Open(resp.FilePath)
		if openErr != nil {
			logx.Errorf("打开授权书文件失败: filePath=%s, error=%v", resp.FilePath, openErr)
			result.HttpResult(r, w, nil, errors.New("授权书文件不存在"))
			return
		}
		defer file.Close()

		fileInfo, statErr := file.Stat()
		if statErr != nil {
			logx.Errorf("读取授权书文件信息失败: filePath=%s, error=%v", resp.FilePath, statErr)
			result.HttpResult(r, w, nil, errors.New("授权书文件不可用"))
			return
		}

		escapedName := url.PathEscape(resp.FileName)
		w.Header().Set("Content-Type", "application/pdf")
		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"; filename*=UTF-8''%s", escapedName, escapedName))
		w.Header().Set("Content-Length", strconv.FormatInt(fileInfo.Size(), 10))

		http.ServeContent(w, r, resp.FileName, fileInfo.ModTime(), file)
	}
}
