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"
)

// 获取相册详情
func GetAlbum(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudAlbumItem, 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.Preload("Photos").First(&album).Error; err != nil {
		printer.Error("Album not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 转换照片数据
	var photos []*pb.CloudPhotoItem
	for _, photo := range album.Photos {
		photos = append(photos, &pb.CloudPhotoItem{
			Id:          uint64(photo.ID),
			Identity:    photo.Identity,
			AlbumId:     uint64(photo.AlbumID),
			Title:       photo.Title,
			Description: photo.Description,
			FilePath:    photo.FilePath,
			FileSize:    photo.FileSize,
			MimeType:    photo.MimeType,
			Width:       int32(photo.Width),
			Height:      int32(photo.Height),
			TakenAt:     photo.TakenAt.Format(time.RFC3339),
			Location:    photo.Location,
			Tags:        photo.Tags,
			CreatedAt:   photo.CreatedAt.Format(time.RFC3339),
			UpdatedAt:   photo.UpdatedAt.Format(time.RFC3339),
		})
	}

	reply = &pb.CloudAlbumItem{
		Id:          uint64(album.ID),
		Identity:    album.Identity,
		Name:        album.Name,
		Description: album.Description,
		CoverPhoto:  album.CoverPhoto,
		IsPrivate:   album.IsPrivate,
		CreatedAt:   album.CreatedAt.Format(time.RFC3339),
		UpdatedAt:   album.UpdatedAt.Format(time.RFC3339),
		Photos:      photos,
	}

	return reply, nil
}
