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/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/types"
)

// 获取空间数据
func Get(ctx context.Context, in *pb.Empty) (reply *pb.CloudSpace, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// logic code
	var space models.CloudSpace
	if err := impl.DBService.Where("passport_id = ?", auth.ID).First(&space).Error; err != nil {
		// 如果不存在，创建默认空间记录
		space = models.CloudSpace{
			Std_IICUDS: types.Std_IICUDS{
				Identity: "default",
			},
			Std_Passport: types.Std_Passport{
				PassportID:       auth.ID,
				PassportIdentity: auth.Identity,
			},
			KeyIdentifier: "default",
			TotalStorage:  100 * 1024 * 1024 * 1024, // 100GB
			UsedStorage:   0,
			MaxStorage:    100 * 1024 * 1024 * 1024, // 100GB
			FileCount:     0,
			AlbumCount:    0,
			PhotoCount:    0,
			NoteCount:     0,
			BookmarkCount: 0,
			PrivateCount:  0,
		}
		if err := impl.DBService.Create(&space).Error; err != nil {
			printer.Error("Create space error: %v", err)
			return nil, err
		}
	}

	// 统计各种数据
	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
}
