package upload

import (
	"context"
	"net/http"
	"server/internal/model"
	"server/internal/service"
	"server/utility/ecode"
	"server/utility/oss"

	"github.com/gogf/gf/v2/errors/gerror"
)

type sUpload struct{}

func New() service.IUpload {
	return &sUpload{}
}
func init() {
	service.RegisterUpload(New())
}
func (s *sUpload) UploadImage(ctx context.Context, in *model.UploadImageIn) (*model.UploadImageOut, error) {
	if in.File == nil {
		return nil, gerror.NewCode(ecode.Fail.Sub("image_file_required").Code())
	}
	// 校验文件类型（只允许图片）
	contentType := in.File.Header.Get("Content-Type")
	if contentType == "" {
		f, err := in.File.Open()
		if err != nil {
			return nil, gerror.NewCode(ecode.Fail.Sub("image_read_failed").Code())
		}
		defer f.Close()
		buf := make([]byte, 512)
		_, err = f.Read(buf)
		if err != nil {
			return nil, gerror.NewCode(ecode.Fail.Sub("image_read_failed").Code())
		}
		contentType = http.DetectContentType(buf)
	}
	if len(contentType) < 6 || contentType[:6] != "image/" {
		return nil, gerror.NewCode(ecode.Fail.Sub("image_type_invalid").Code())
	}
	allowedTypes := map[string]bool{
		"image/jpeg": true,
		"image/png":  true,
		"image/gif":  true,
		"image/webp": true,
	}
	if !allowedTypes[contentType] {
		return nil, gerror.NewCode(ecode.Fail.Sub("image_format_invalid").Code())
	}
	// 校验文件大小（不超过1MB）
	if in.File.Size > 1*1024*1024 {
		return nil, gerror.NewCode(ecode.Fail.Sub("image_size_exceeded").Code())
	}
	client := oss.GetOSSClient("amazon_s3")
	if client == nil {
		return nil, gerror.NewCode(ecode.Fail.Code())
	}
	url, err := client.Upload(in.File, in.Type)
	if err != nil {
		return nil, err
	}
	return &model.UploadImageOut{ImageUrl: url}, nil
}
