package album

import (
	"context"
	"strings"
	"time"

	"bsm/full/module/base/cloud/internal/impl"
	"bsm/full/module/base/cloud/internal/models"
	pb "bsm/full/module/base/cloud/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/bsm-sdk/core/utils"
)

// 上传照片
func UploadPhoto(ctx context.Context, in *pb.CloudPhotoItem) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request
	if in.AlbumId == 0 {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.FilePath) == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	// 验证相册是否存在且属于当前用户
	var album models.CloudAlbum
	if err := impl.DBService.Where("id = ? AND passport_id = ?", in.AlbumId, auth.ID).First(&album).Error; err != nil {
		printer.Error("Album not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 解析拍摄时间
	var takenAt time.Time
	if in.TakenAt != "" {
		if t, err := time.Parse(time.RFC3339, in.TakenAt); err == nil {
			takenAt = t
		} else {
			takenAt = time.Now()
		}
	} else {
		takenAt = time.Now()
	}

	record := models.CloudPhoto{
		Std_IICUDS: types.Std_IICUDS{
			Identity: utils.UUID(),
		},
		CloudBase: models.CloudBase{
			CloudID:       album.CloudID,
			CloudIdentity: album.CloudIdentity,
		},
		AlbumID:     uint(in.AlbumId),
		Title:       in.Title,
		Description: in.Description,
		FilePath:    in.FilePath,
		FileSize:    in.FileSize,
		MimeType:    in.MimeType,
		Width:       int(in.Width),
		Height:      int(in.Height),
		TakenAt:     takenAt,
		Location:    in.Location,
		Tags:        in.Tags,
	}

	if err := impl.DBService.Create(&record).Error; err != nil {
		printer.Error("Create photo error: %v", err)
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Details: record.Identity,
		Timeseq: time.Now().UnixMilli(),
	}, nil
}
