package disk

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 GetFile(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudDiskFileItem, 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 file models.CloudDiskFile
	query := 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)

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

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

	// 构建目录信息
	var directory *pb.CloudDiskDirItem
	if file.Directory != nil {
		directory = &pb.CloudDiskDirItem{
			Id:        uint64(file.Directory.ID),
			Identity:  file.Directory.Identity,
			Name:      file.Directory.Name,
			Path:      file.Directory.Path,
			CreatedAt: file.Directory.CreatedAt.Format(time.RFC3339),
			UpdatedAt: file.Directory.UpdatedAt.Format(time.RFC3339),
		}
	}

	reply = &pb.CloudDiskFileItem{
		Id:           uint64(file.ID),
		Identity:     file.Identity,
		DirectoryId:  uint64(*file.DirectoryID),
		Name:         file.Name,
		OriginalName: file.OriginalName,
		Size:         file.Size,
		MimeType:     file.MimeType,
		StoragePath:  file.StoragePath,
		Hash:         file.Hash,
		CreatedAt:    file.CreatedAt.Format(time.RFC3339),
		UpdatedAt:    file.UpdatedAt.Format(time.RFC3339),
		Directory:    directory,
	}

	return reply, nil
}
