import { api } from '../api/client'
import type { CopyMissionData, CopySimilarAccountData } from '../types/copyMission'

export type SimilarAccountPatchStatus = 'recommended' | 'pinned' | 'excluded' | 'promoted'

export function copyMissionSimilarAccountPath(
  personaId: string,
  missionId: string,
  username: string,
): string {
  const user = encodeURIComponent(username.replace(/^@/, ''))
  return `/api/v1/personas/${encodeURIComponent(personaId)}/copy-missions/${encodeURIComponent(missionId)}/similar-accounts/${user}`
}

export async function patchCopyMissionSimilarAccount(
  personaId: string,
  missionId: string,
  username: string,
  status: SimilarAccountPatchStatus,
): Promise<CopyMissionData> {
  return api.patch<CopyMissionData>(
    copyMissionSimilarAccountPath(personaId, missionId, username),
    { status },
    { auth: true },
  )
}

export function sortSimilarAccounts(list: CopySimilarAccountData[]): CopySimilarAccountData[] {
  const rank = (item: CopySimilarAccountData) => {
    if (item.status === 'pinned') return 0
    if (item.status === 'excluded') return 2
    return 1
  }
  return [...list].sort((a, b) => {
    const rankDiff = rank(a) - rank(b)
    if (rankDiff !== 0) return rankDiff
    const aVerified = a.author_verified ? 1 : 0
    const bVerified = b.author_verified ? 1 : 0
    if (aVerified !== bVerified) return bVerified - aVerified
    return (b.engagement_score ?? 0) - (a.engagement_score ?? 0)
  })
}

export function similarAccountStatusLabel(status?: string): string {
  switch (status) {
    case 'pinned':
      return '已釘選'
    case 'excluded':
      return '已排除'
    case 'promoted':
      return '已升級'
    default:
      return ''
  }
}