package copy_mission

import (
	"context"
	"fmt"
	"strings"

	copydraftdomain "haixun-backend/internal/model/copy_draft/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *DeleteCopyMissionMatrixDraftsLogic) DeleteCopyMissionMatrixDrafts(
	req *types.DeleteCopyMissionMatrixDraftsHandlerReq,
) (*types.DeleteCopyMissionMatrixDraftsData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.PersonaID)
	missionID := strings.TrimSpace(req.ID)
	if _, err := l.svcCtx.CopyMission.Get(l.ctx, tenantID, uid, personaID, missionID); err != nil {
		return nil, err
	}
	deleted, err := l.svcCtx.CopyDraft.DeleteMissionMatrixDrafts(l.ctx, copydraftdomain.DeleteMissionMatrixDraftsRequest{
		TenantID:  tenantID,
		OwnerUID:  uid,
		PersonaID: personaID,
		MissionID: missionID,
		DraftIDs:  req.DraftIDs,
	})
	if err != nil {
		return nil, err
	}
	message := fmt.Sprintf("已刪除 %d 篇矩陣草稿", deleted)
	if len(req.DraftIDs) == 0 {
		message = fmt.Sprintf("已刪除全部 %d 篇矩陣草稿", deleted)
	}
	return &types.DeleteCopyMissionMatrixDraftsData{
		Deleted: deleted,
		Message: message,
	}, nil
}