// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package copy_mission

import (
	"context"
	"strings"

	missionentity "haixun-backend/internal/model/copy_mission/domain/entity"
	missiondomain "haixun-backend/internal/model/copy_mission/domain/usecase"
	threadsaccountdomain "haixun-backend/internal/model/threads_account/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

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

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

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

func (l *PatchCopyMissionSimilarAccountLogic) PatchCopyMissionSimilarAccount(req *types.PatchSimilarAccountHandlerReq) (*types.CopyMissionData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	item, err := l.svcCtx.CopyMission.PatchSimilarAccount(l.ctx, missiondomain.PatchSimilarAccountRequest{
		TenantID:  tenantID,
		OwnerUID:  uid,
		PersonaID: strings.TrimSpace(req.PersonaID),
		MissionID: strings.TrimSpace(req.ID),
		Username:  strings.TrimSpace(req.Username),
		Status:    req.Status,
	})
	if err != nil {
		return nil, err
	}
	if status := strings.TrimSpace(req.Status); status == missionentity.SimilarAccountStatusExcluded || status == missionentity.SimilarAccountStatusRecommended {
		if research, researchErr := l.svcCtx.Placement.ResearchSettings(l.ctx, tenantID, uid); researchErr == nil {
			if memberCtx, memberErr := l.svcCtx.ThreadsAccount.ResolveMemberPlacementContext(l.ctx, tenantID, uid, research); memberErr == nil && memberCtx.ActiveAccountID != "" {
				username := strings.TrimSpace(strings.TrimPrefix(req.Username, "@"))
				if username != "" {
					_ = l.svcCtx.ThreadsAccount.UpsertKnownAccountsFromScan(l.ctx, threadsaccountdomain.UpsertKnownAccountsFromScanRequest{
						TenantID:  tenantID,
						OwnerUID:  uid,
						AccountID: memberCtx.ActiveAccountID,
						SimilarAccounts: []missionentity.SimilarAccount{{
							Username: username,
							Status:   status,
						}},
					})
				}
			}
		}
	}
	data := toCopyMissionData(*item)
	return &data, nil
}
