package album

import (
	"context"
	"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/vars"
)

// 移动照片到其他相册
func MovePhoto(ctx context.Context, in *pb.MovePhotoRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request
	if in.PhotoId == 0 || in.NewAlbumId == 0 {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	// 验证照片是否存在且属于当前用户
	var photo models.CloudPhoto
	if err := impl.DBService.Joins("JOIN cloud_albums ON cloud_photos.album_id = cloud_albums.id").
		Where("cloud_photos.id = ? AND cloud_albums.passport_id = ?", in.PhotoId, auth.ID).
		First(&photo).Error; err != nil {
		printer.Error("Photo not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

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

	// 更新照片的相册ID
	photo.AlbumID = uint(in.NewAlbumId)
	photo.CloudID = newAlbum.CloudID
	photo.CloudIdentity = newAlbum.CloudIdentity

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

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