package taskboard

import (
	"context"
	"strings"
	"time"
)

func (txs TxStore) ResolvePrivateAgentContextContributionCapability(ctx context.Context, request ResolvePrivateAgentContextContributionCapabilityRequest) (ResolvePrivateAgentContextContributionCapabilityResponse, error) {
	workspaceID, err := request.Context.requireWorkspaceID()
	if err != nil {
		return ResolvePrivateAgentContextContributionCapabilityResponse{}, err
	}
	userID, _, err := request.Context.requireUser()
	if err != nil {
		return ResolvePrivateAgentContextContributionCapabilityResponse{}, err
	}

	target, viewerMemberID, err := txs.resolveTaskCollaboratorTargetForUser(ctx, txs.db, userID, workspaceID, request.Task, request.Scope, taskReadChannelAction)
	if err != nil {
		return ResolvePrivateAgentContextContributionCapabilityResponse{}, err
	}
	canManage, err := txs.canManagePrivateAgentContextTarget(ctx, txs.db, workspaceID, viewerMemberID, target.ExecutionOwnerMemberID)
	if err != nil {
		return ResolvePrivateAgentContextContributionCapabilityResponse{}, err
	}

	response := basePrivateAgentContextContributionCapability(target, canManage)
	if strings.TrimSpace(viewerMemberID) == strings.TrimSpace(target.ExecutionOwnerMemberID) {
		response.Relation = "owner"
		response.RelationSource = &PrivateAgentContextRelationSource{Kind: "owner", ScopeType: target.ScopeType, ScopeID: target.ScopeID}
		response.CanContributeContext = true
		response.CanWake = true
		return response, nil
	}

	relation, err := txs.loadPrivateAgentMentionCandidatePeopleRelation(ctx, txs.db, workspaceID, viewerMemberID, target, target.ExecutionOwnerMemberID, time.Now().UTC())
	if err != nil {
		return ResolvePrivateAgentContextContributionCapabilityResponse{}, err
	}
	if relation != nil {
		response.Relation = "collaborator"
		response.RelationSource = relation
		response.CanContributeContext = true
		response.CanWake = true
		return response, nil
	}

	return response, nil
}

func basePrivateAgentContextContributionCapability(target taskCollaboratorTarget, canManage bool) ResolvePrivateAgentContextContributionCapabilityResponse {
	return ResolvePrivateAgentContextContributionCapabilityResponse{
		TargetScopeType:        target.ScopeType,
		TargetScopeID:          target.ScopeID,
		ExecutionOwnerMemberID: strings.TrimSpace(target.ExecutionOwnerMemberID),
		Relation:               "none",
		CanContributeContext:   false,
		CanWake:                false,
		CanShare:               canManage,
	}
}
