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 SetCoverPhoto(ctx context.Context, in *pb.SetCoverPhotoRequest) (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 || in.PhotoId == 0 {
		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 photo models.CloudPhoto
	if err := impl.DBService.Where("id = ? AND album_id = ?", in.PhotoId, in.AlbumId).First(&photo).Error; err != nil {
		printer.Error("Photo not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 更新相册的封面照片
	album.CoverPhoto = photo.FilePath
	if err := impl.DBService.Save(&album).Error; err != nil {
		printer.Error("Set cover photo error: %v", err)
		return nil, errcode.ErrDB
	}

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