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

	// validate request
	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.First(&photo).Error; err != nil {
		printer.Error("Photo not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 更新字段
	photo.Title = in.Title
	photo.Description = in.Description
	photo.Location = in.Location
	photo.Tags = in.Tags

	// 更新拍摄时间
	if in.TakenAt != "" {
		if t, err := time.Parse(time.RFC3339, in.TakenAt); err == nil {
			photo.TakenAt = t
		}
	}

	if err := impl.DBService.Save(&photo).Error; err != nil {
		printer.Error("Update photo error: %v", err)
		return nil, errcode.ErrDB
	}

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