package note

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

// 删除附件
func DeleteAttachment(ctx context.Context, in *pb.IdentRequest) (reply *pb.StatusReply, 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 attachment models.NoteAttachment
	query := impl.DBService.Joins("JOIN cloud_notes ON note_attachments.note_id = cloud_notes.id").
		Where("cloud_notes.passport_id = ?", auth.ID)

	if in.Id > 0 {
		query = query.Where("note_attachments.id = ?", in.Id)
	} else {
		// 注意：NoteAttachment模型没有identity字段，这里假设通过ID删除
		query = query.Where("note_attachments.id = ?", in.Id)
	}

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

	// 删除附件
	if err := impl.DBService.Delete(&attachment).Error; err != nil {
		printer.Error("Delete attachment error: %v", err)
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Details: vars.OK,
		Timeseq: time.Now().UnixMilli(),
	}, nil
}
