import { writePublishLog } from "@/lib/logging/publish-logs";
import {
  isValidLinkedInMemberId,
  probeLinkedInAccessToken,
} from "@/lib/social/linkedin-probe";

function toPersonUrn(id: string): string {
  if (id.startsWith("urn:li:person:")) return id;
  return `urn:li:person:${id}`;
}

/** Resolve LinkedIn member id from stored externalId or live API (needs openid + w_member_social). */
export async function resolveLinkedInMemberId(
  accessToken: string,
  externalId?: string | null,
  context?: { projectId?: string; postId?: string },
): Promise<string> {
  const probe = await probeLinkedInAccessToken(accessToken, externalId);

  if (probe.ok && probe.personUrn) {
    return probe.personUrn;
  }

  await writePublishLog({
    level: "error",
    action: "linkedin_member_id_failed",
    projectId: context?.projectId,
    postId: context?.postId,
    platform: "linkedin",
    message: probe.recommendation,
    details: { attempts: probe.attempts },
  });

  throw new Error(`Could not resolve LinkedIn member ID. ${probe.recommendation}`);
}

/** Returns bare member id (no urn prefix) for storage as externalId. */
export async function fetchLinkedInMemberId(
  accessToken: string,
  context?: { projectId?: string },
): Promise<string> {
  const urn = await resolveLinkedInMemberId(accessToken, null, context);
  return urn.replace(/^urn:li:person:/, "");
}

export function isLinkedInExternalIdValid(externalId?: string | null): boolean {
  return isValidLinkedInMemberId(externalId);
}
