package copy_mission

import (
	"context"
	"strings"

	missiondomain "haixun-backend/internal/model/copy_mission/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

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

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

func (l *CreateCopyMissionLogic) CreateCopyMission(req *types.CreateCopyMissionHandlerReq) (*types.CopyMissionData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.PersonaID)
	persona, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID)
	if err != nil {
		return nil, err
	}
	initialMap, initialTags := seedMissionResearchFromPersona(*persona)
	createReq := missiondomain.CreateRequest{
		TenantID:  tenantID,
		OwnerUID:  uid,
		PersonaID: personaID,
		Label:     req.Label,
		SeedQuery: req.SeedQuery,
		Brief:     req.Brief,
	}
	if initialMap != nil {
		createReq.InitialResearchMap = initialMap
		createReq.InitialSelectedTags = initialTags
	}
	item, err := l.svcCtx.CopyMission.Create(l.ctx, createReq)
	if err != nil {
		return nil, err
	}
	data := toCopyMissionData(*item)
	return &data, nil
}
