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 GetPhoto(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudPhotoItem, 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 photo models.CloudPhoto
	query := impl.DBService.Joins("JOIN cloud_albums ON cloud_photos.album_id = cloud_albums.id").
		Where("cloud_albums.passport_id = ?", auth.ID)

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

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

	// 转换相册数据
	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),
	}

	reply = &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,
	}

	return reply, nil
}
