package space

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 GetByKeyIdentifier(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudSpace, 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 space models.CloudSpace
	query := impl.DBService.Where("passport_id = ?", auth.ID)

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

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

	// 统计各种数据
	var fileCount, albumCount, photoCount, noteCount, bookmarkCount, privateCount int64
	var usedStorage int64

	// 统计文件数量和存储空间
	if err := impl.DBService.Model(&models.CloudDiskFile{}).
		Joins("JOIN cloud_disk_dirs ON cloud_disk_files.directory_id = cloud_disk_dirs.id").
		Where("cloud_disk_dirs.passport_id = ?", auth.ID).
		Count(&fileCount).Error; err == nil {
		var files []models.CloudDiskFile
		impl.DBService.Joins("JOIN cloud_disk_dirs ON cloud_disk_files.directory_id = cloud_disk_dirs.id").
			Where("cloud_disk_dirs.passport_id = ?", auth.ID).
			Find(&files)
		for _, file := range files {
			usedStorage += file.Size
		}
	}

	// 统计相册数量
	impl.DBService.Model(&models.CloudAlbum{}).Where("passport_id = ?", auth.ID).Count(&albumCount)

	// 统计照片数量
	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(&photoCount)

	// 统计笔记数量
	impl.DBService.Model(&models.CloudNote{}).Where("passport_id = ?", auth.ID).Count(&noteCount)

	// 统计书签数量
	impl.DBService.Model(&models.CloudBookmark{}).Where("passport_id = ?", auth.ID).Count(&bookmarkCount)

	// 统计隐私数据数量
	impl.DBService.Model(&models.CloudPrivate{}).Where("passport_id = ?", auth.ID).Count(&privateCount)

	// 更新统计数据
	space.UsedStorage = usedStorage
	space.FileCount = int(fileCount)
	space.AlbumCount = int(albumCount)
	space.PhotoCount = int(photoCount)
	space.NoteCount = int(noteCount)
	space.BookmarkCount = int(bookmarkCount)
	space.PrivateCount = int(privateCount)

	if err := impl.DBService.Save(&space).Error; err != nil {
		printer.Error("Update space error: %v", err)
		// 不返回错误，继续执行
	}

	reply = &pb.CloudSpace{
		Id:            uint64(space.ID),
		Identity:      space.Identity,
		TotalStorage:  space.TotalStorage,
		UsedStorage:   space.UsedStorage,
		MaxStorage:    space.MaxStorage,
		FileCount:     int32(space.FileCount),
		AlbumCount:    int32(space.AlbumCount),
		PhotoCount:    int32(space.PhotoCount),
		NoteCount:     int32(space.NoteCount),
		BookmarkCount: int32(space.BookmarkCount),
		PrivateCount:  int32(space.PrivateCount),
		CreatedAt:     space.CreatedAt.Format(time.RFC3339),
		UpdatedAt:     space.UpdatedAt.Format(time.RFC3339),
	}

	return reply, nil
}
