package logic

import (
	"context"

	"errors"
	"sundynix-micro-go/app/file/model"
	"sundynix-micro-go/app/file/rpc/file"
	"sundynix-micro-go/app/file/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

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

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

// 通过MD5检查文件是否存在
func (l *CheckFileByMd5Logic) CheckFileByMd5(in *file.CheckFileByMd5Req) (*file.CheckFileByMd5Resp, error) {
	if in.Md5 == "" {
		return &file.CheckFileByMd5Resp{Exists: false}, nil
	}

	var ossRecord model.SundynixOss
	err := l.svcCtx.DB.Where("md5 = ?", in.Md5).First(&ossRecord).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &file.CheckFileByMd5Resp{Exists: false}, nil
		}
		return nil, err
	}

	return &file.CheckFileByMd5Resp{
		Exists: true,
		File: &file.FileInfo{
			Id:        ossRecord.ID,
			Name:      ossRecord.Name,
			Url:       ossRecord.Url,
			Tag:       ossRecord.Tag,
			Key:       ossRecord.Key,
			Suffix:    ossRecord.Suffix,
			Md5:       ossRecord.MD5,
			CreatedAt: ossRecord.CreatedAt.Unix(),
		},
	}, nil
}
