package disk

import (
	"context"
	"strings"
	"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/service"
)

// 搜索文件
func SearchFiles(ctx context.Context, in *pb.FetchRequest) (reply *pb.ListFilesResponse, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request page_no,page_size.
	if in.GetPageNo() < 1 {
		in.PageNo = 1
	}
	if in.GetPageSize() < 10 {
		in.PageSize = 50
	}

	// logic code
	var files []models.CloudDiskFile
	var total int64

	// 构建搜索查询
	query := 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)

	// 添加搜索条件
	if keyword, exists := in.Params["keyword"]; exists && keyword != "" {
		searchKeyword := "%" + strings.ToLower(keyword) + "%"
		query = query.Where("LOWER(cloud_disk_files.name) LIKE ? OR LOWER(cloud_disk_files.original_name) LIKE ?", searchKeyword, searchKeyword)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 分页查询
	offset := (in.PageNo - 1) * in.PageSize
	if err := query.
		Preload("Directory").
		Order("cloud_disk_files.created_at DESC").
		Offset(int(offset)).
		Limit(int(in.PageSize)).
		Find(&files).Error; err != nil {
		return nil, err
	}

	// 转换数据
	var fileItems []*pb.CloudDiskFileItem
	for _, file := range files {
		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),
			}
		}

		fileItems = append(fileItems, &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,
		})
	}

	reply = &pb.ListFilesResponse{
		Files: fileItems,
		Total: total,
	}

	return reply, nil
}
