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

// 获取相册列表
func ListAlbums(ctx context.Context, in *pb.FetchRequest) (reply *pb.ListAlbumsResponse, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request page_no,page_size.
	if in.GetPageNo() < 1 {
		in.PageNo = 1
	}
	if in.GetPageSize() < 10 {
		in.PageSize = 50
	}

	// logic code
	var albums []models.CloudAlbum
	var total int64

	// 获取总数
	if err := impl.DBService.Model(&models.CloudAlbum{}).Where("passport_id = ?", auth.ID).Count(&total).Error; err != nil {
		return nil, err
	}

	// 分页查询
	offset := (in.PageNo - 1) * in.PageSize
	if err := impl.DBService.Where("passport_id = ?", auth.ID).
		Preload("Photos").
		Order("created_at DESC").
		Offset(int(offset)).
		Limit(int(in.PageSize)).
		Find(&albums).Error; err != nil {
		return nil, err
	}

	// 转换数据
	var albumItems []*pb.CloudAlbumItem
	for _, album := range albums {
		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),
			})
		}

		albumItems = append(albumItems, &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,
		})
	}

	reply = &pb.ListAlbumsResponse{
		Albums: albumItems,
		Total:  total,
	}

	return reply, nil
}
