package logic

import (
	"context"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
	"sundynix-micro-go/app/file/model"
	"sundynix-micro-go/app/file/rpc/file"
	"sundynix-micro-go/app/file/rpc/internal/svc"
)

type GetFileByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetFileByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFileByIdLogic {
	return &GetFileByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 根据ID获取文件信息
func (l *GetFileByIdLogic) GetFileById(in *file.GetFileByIdReq) (*file.GetFileByIdResp, error) {
	var oss model.SundynixOss
	err := l.svcCtx.DB.Where("id = ?", in.Id).First(&oss).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, status.Error(codes.NotFound, "文件不存在")
		}
		l.Errorf("查询文件失败: %v", err)
		return nil, status.Error(codes.Internal, "查询文件失败")
	}

	return &file.GetFileByIdResp{
		File: convertOssToProto(&oss),
	}, nil
}

func convertOssToProto(oss *model.SundynixOss) *file.FileInfo {
	return &file.FileInfo{
		Id:        oss.ID,
		Name:      oss.Name,
		Url:       oss.Url,
		Tag:       oss.Tag,
		Key:       oss.Key,
		Suffix:    oss.Suffix,
		Md5:       oss.MD5,
		CreatedAt: oss.CreatedAt.Unix(),
	}
}
