import 'server-only' import type { Payload } from 'payload' import { isContactSearchQueryReady, normalizeContactSearchQuery } from '@/lib/contactSearchQuery' import { isPopulatedRelationship, relationshipId } from '@/lib/relationship' import type { CampaignUser, Contact, Leadership } from '@/payload-types' export type ActivityLeadershipOption = { id: number label: string } const LEADERSHIP_SEARCH_LIMIT = 20 const leadershipLabel = (leadership: Leadership): string | null => { const id = relationshipId(leadership.id) if (!id) return null const contact = leadership.contact return isPopulatedRelationship(contact) ? contact.name : `Liderança #${id}` } /** * Engaged leaderships visible to the actor (for linking an activity to a leadership). * Uses overrideAccess: false so Payload row-level access applies. */ export const searchActivityLeadershipOptions = async ( payload: Pick, user: CampaignUser, query: string, ): Promise => { const normalizedQuery = typeof query === 'string' ? query : '' if (!isContactSearchQueryReady(normalizedQuery)) return [] const { trimmed, digits } = normalizeContactSearchQuery(normalizedQuery) const result = await payload.find({ collection: 'leadership', where: { and: [ { supportStatus: { equals: 'engajado' } }, { or: [ { 'contact.name': { contains: trimmed } }, { 'contact.phones.value': { contains: digits || trimmed } }, ], }, ], }, depth: 1, limit: LEADERSHIP_SEARCH_LIMIT, select: { contact: true, supportStatus: true, }, user, overrideAccess: false, }) return result.docs .map((doc) => { const leadership = doc as Leadership const id = relationshipId(leadership.id) const label = leadershipLabel(leadership) if (!id || !label) return null return { id, label } }) .filter((option): option is ActivityLeadershipOption => option !== null) .sort((left, right) => left.label.localeCompare(right.label, 'pt-BR')) }