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 DeleteAlbum(ctx context.Context, in *pb.IdentRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request id,identity.
	if in.Id == 0 && in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	var album models.CloudAlbum
	query := impl.DBService.Where("passport_id = ?", auth.ID)

	if in.Id > 0 {
		query = query.Where("id = ?", in.Id)
	} else {
		query = query.Where("identity = ?", in.Identity)
	}

	if err := query.First(&album).Error; err != nil {
		printer.Error("Album not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 删除相册下的所有照片
	if err := impl.DBService.Where("album_id = ?", album.ID).Delete(&models.CloudPhoto{}).Error; err != nil {
		printer.Error("Delete photos error: %v", err)
		return nil, errcode.ErrDB
	}

	// 删除相册
	if err := impl.DBService.Delete(&album).Error; err != nil {
		printer.Error("Delete album error: %v", err)
		return nil, errcode.ErrDB
	}

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