package persona

import (
	"context"
	"fmt"

	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

type PrunePersonaCopyDraftsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPrunePersonaCopyDraftsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PrunePersonaCopyDraftsLogic {
	return &PrunePersonaCopyDraftsLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *PrunePersonaCopyDraftsLogic) PrunePersonaCopyDrafts(req *types.PrunePersonaCopyDraftsHandlerReq) (*types.PrunePersonaCopyDraftsData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := req.ID
	if _, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID); err != nil {
		return nil, err
	}
	keep := int(req.Keep)
	if keep <= 0 {
		keep = 40
	}
	deleted, err := l.svcCtx.CopyDraft.PruneIdleDrafts(l.ctx, tenantID, uid, personaID, keep)
	if err != nil {
		return nil, err
	}
	message := fmt.Sprintf("已保留最近 %d 篇草稿", keep)
	if deleted > 0 {
		message = fmt.Sprintf("已刪除 %d 篇多餘舊草稿，保留最近 %d 篇", deleted, keep)
	}
	return &types.PrunePersonaCopyDraftsData{
		Deleted: deleted,
		Kept:    keep,
		Message: message,
	}, nil
}
