package fileStorage

import (
	errs "backend/pkg/library/errors"
	"net/http"

	"backend/internal/logic/fileStorage"
	"backend/internal/svc"
	"backend/internal/types"

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

// 上傳影片檔案
func UploadVideoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.UploadVideoReq
		if err := httpx.Parse(r, &req); err != nil {
			e := errs.InputInvalidFormatError(err.Error())
			httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.Resp{
				Code:    e.DisplayCode(),
				Message: err.Error(),
			})
			return
		}

		// 解析 multipart form，限制 100MB
		if err := r.ParseMultipartForm(100 << 20); err != nil {
			e := errs.InputInvalidFormatError("failed to parse multipart form: " + err.Error())
			httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.Resp{
				Code:    e.DisplayCode(),
				Message: err.Error(),
			})
			return
		}

		// 獲取文件
		file, header, err := r.FormFile("file")
		if err != nil {
			e := errs.InputInvalidFormatError("failed to get file from form: " + err.Error())
			httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.Resp{
				Code:    e.DisplayCode(),
				Message: err.Error(),
			})
			return
		}
		defer file.Close()

		l := fileStorage.NewUploadVideoLogic(r.Context(), svcCtx)
		resp, err := l.UploadVideo(&req, file, header)
		if err != nil {
			e := errs.FromError(err)
			httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.Resp{
				Code:    e.DisplayCode(),
				Message: e.Error(),
				Error:   e.Unwrap(),
			})
		} else {
			httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, resp)
		}
	}
}
