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 ListPhotos(ctx context.Context, in *pb.FetchRequest) (reply *pb.ListPhotosResponse, 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 photos []models.CloudPhoto
	var total int64

	// 获取总数
	if err := impl.DBService.Model(&models.CloudPhoto{}).
		Joins("JOIN cloud_albums ON cloud_photos.album_id = cloud_albums.id").
		Where("cloud_albums.passport_id = ?", auth.ID).
		Count(&total).Error; err != nil {
		return nil, err
	}

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

	// 转换数据
	var photoItems []*pb.CloudPhotoItem
	for _, photo := range photos {
		// 转换相册数据
		albumItem := &pb.CloudAlbumItem{
			Id:          uint64(photo.Album.ID),
			Identity:    photo.Album.Identity,
			Name:        photo.Album.Name,
			Description: photo.Album.Description,
			CoverPhoto:  photo.Album.CoverPhoto,
			IsPrivate:   photo.Album.IsPrivate,
			CreatedAt:   photo.Album.CreatedAt.Format(time.RFC3339),
			UpdatedAt:   photo.Album.UpdatedAt.Format(time.RFC3339),
		}

		photoItems = append(photoItems, &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),
			Album:       albumItem,
		})
	}

	reply = &pb.ListPhotosResponse{
		Photos: photoItems,
		Total:  total,
	}

	return reply, nil
}
