package api

import (
	"fmt"
	"mime/multipart"
	"net/http"
	"path/filepath"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/tidbcloud/account/commons/config"
	"github.com/tidbcloud/account/thirdparty/cdn"
)

type FileForm struct {
	File *multipart.FileHeader `form:"file" binding:"required"`
}

type UploadFileResp struct {
	FilePath string `json:"filePath"`
	FileLink string `json:"fileLink"`
}

type FilePath struct {
	FilePath string `uri:"file_path" binding:"required"`
}

func UploadFile(c *gin.Context) {
	ctx := c.Request.Context()
	form := &FileForm{}
	err := c.ShouldBind(form)
	if err != nil {
		Fail(c, err, http.StatusBadRequest)
		return
	}

	filename := form.File.Filename
	extName := filepath.Ext(filename)
	key := fmt.Sprintf("%s%s", uuid.NewString(), extName)
	body, err := form.File.Open()
	if err != nil {
		Fail(c, err, http.StatusBadRequest)
		return
	}
	err = cdn.Get().UploadFile(ctx, key, form.File.Size, body)
	if err != nil {
		Fail(c, err, http.StatusInternalServerError)
		return
	}
	Success(c, &UploadFileResp{
		FilePath: key,
		FileLink: fmt.Sprintf("https://%s/api/v1/admin/uploaded/%s", config.Global().ServerConfig.BackendDNS, key),
	}, http.StatusOK)
}

func DownloadFile(c *gin.Context) {
	filePath := &FilePath{}
	err := c.ShouldBindUri(filePath)
	if err != nil {
		Fail(c, err, http.StatusBadRequest)
		return
	}

	path := filePath.FilePath

	_, fileName := filepath.Split(path)
	fileObject, err := cdn.Get().GetCDNFile(path)
	if err != nil {
		Fail(c, err, http.StatusInternalServerError)
		return
	}
	c.DataFromReader(http.StatusOK, fileObject.ContentLength, config.Global().ServerConfig.CDNFileContentType, fileObject.File, map[string]string{
		"Content-Disposition": "attachment; filename=" + fileName,
	})
}
