package osshttp

import (
	"fmt"
	oss2 "legalgo-BE-go/internal/domain/oss"
	"legalgo-BE-go/internal/services/oss"
	"legalgo-BE-go/internal/utilities/response"
	"net/http"

	"github.com/go-chi/chi/v5"
)

const _oneMB = 1 << 20
const _maxUploadSize = 2 * _oneMB
const _folderName = "/file"

func RegisterUploadFile(ossService oss.OSSService, router chi.Router) {
	router.Post("/file", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		// Limit the size of the request body to prevent very large uploads.
		r.Body = http.MaxBytesReader(w, r.Body, int64(_maxUploadSize))
		if err := r.ParseMultipartForm(int64(_maxUploadSize)); err != nil {
			response.ResponseWithErrorCode(
				ctx,
				w,
				err,
				response.ErrBadRequest.Code,
				response.ErrBadRequest.HttpCode,
				"Failed to parse multipart form",
			)
			return
		}

		// Retrieve the file from the form.
		file, header, err := r.FormFile("file")
		if err != nil {
			response.ResponseWithErrorCode(
				ctx,
				w,
				err,
				response.ErrBadRequest.Code,
				response.ErrBadRequest.HttpCode,
				"Failed to retrieve file",
			)
			return
		}
		defer file.Close()

		// Check if file size exceeds the maximum limit.
		if header.Size > int64(_maxUploadSize) {
			response.ResponseWithErrorCode(
				ctx,
				w,
				fmt.Errorf("file too big"),
				response.ErrBadRequest.Code,
				response.ErrBadRequest.HttpCode,
				fmt.Sprintf("The file is too big. The maximum size is %d MB", _maxUploadSize/_oneMB),
			)
			return
		}

		// Prepare the request for the OSS service.
		uploadReq := &oss2.UploadFileRequest{
			FileHeader: header,
			FolderName: _folderName,
		}

		// Call the OSS service to handle the file upload.
		result, err := ossService.UploadFile(ctx, uploadReq)
		if err != nil {
			response.ResponseWithErrorCode(
				ctx,
				w,
				err,
				response.ErrBadRequest.Code,
				response.ErrBadRequest.HttpCode,
				err.Error(),
			)
			return
		}

		// Return a successful JSON response.
		response.RespondJsonSuccess(ctx, w, struct {
			Message string      `json:"message"`
			Data    interface{} `json:"data"`
		}{
			Message: "File uploaded successfully.",
			Data:    result,
		})
	})
}
