import type { ConnectedAccount } from "@/types/workflow";
import {
  getAccountHealth,
  isAccountPublishReady,
  isSimulatedToken,
} from "@/lib/social/token-validation";
import { isPlatformPublishReady } from "@/lib/social/platforms";
import type { StoredSocialAccount } from "@/lib/storage/social-accounts";
import { mergeAccountsForPublish } from "@/lib/storage/social-accounts";
import { getLinkedInPublishBlockReason } from "@/lib/social/ensure-publish-tokens";
import {
  resolveConnectedPublishPlatforms,
  resolvePublishReadyPlatforms,
} from "@/lib/social/publish-platforms";

export { resolveConnectedPublishPlatforms, resolvePublishReadyPlatforms };

export function getAccountPublishBlockReason(
  account: ConnectedAccount & { publishToken?: string | null },
): string | null {
  if (!isPlatformPublishReady(account.platform)) return null;
  if (!account.connected) {
    return `${account.label} is not connected`;
  }
  const token = account.publishToken ?? account.accessToken;
  if (token && isSimulatedToken(account)) {
    return `${account.label} uses a demo token — reconnect with OAuth`;
  }
  const health = getAccountHealth(account);
  if (health === "expired") {
    return `${account.label} token expired — reconnect in Connected Accounts`;
  }
  if (health === "error") {
    return `${account.label} connection error — disconnect and reconnect`;
  }
  if (!token && (account.platform === "facebook" || account.platform === "instagram")) {
    return `${account.label} missing page token — reconnect Meta/Facebook`;
  }
  if (account.platform === "linkedin" && !token) {
    return "LinkedIn missing access token — reconnect in Connected Accounts";
  }
  if (isAccountPublishReady(account)) return null;
  return `${account.label} is not publish-ready`;
}

export function summarizePublishAccounts(input: {
  clientAccounts: ConnectedAccount[];
  serverAccounts: StoredSocialAccount[];
}): {
  merged: ConnectedAccount[];
  ready: ConnectedAccount[];
  blockReasons: string[];
  detail: string;
} {
  const merged = mergeAccountsForPublish(input.clientAccounts, input.serverAccounts);
  const publishPlatforms = merged.filter((a) => isPlatformPublishReady(a.platform));
  const ready = merged.filter((a) => isAccountPublishReady(a));
  const blockReasons: string[] = [];

  const linkedInReason = getLinkedInPublishBlockReason(input.serverAccounts);
  if (linkedInReason) blockReasons.push(linkedInReason);

  for (const account of publishPlatforms) {
    const reason = getAccountPublishBlockReason(account);
    if (reason && !blockReasons.includes(reason)) blockReasons.push(reason);
  }

  let detail: string;
  if (ready.length > 0) {
    detail = `Publish-ready: ${ready.map((a) => `${a.label} (${a.profileName})`).join(", ")}.`;
  } else if (blockReasons.length > 0) {
    detail = `${blockReasons[0]} Go to Connected Accounts and reconnect.`;
  } else if (publishPlatforms.some((a) => a.connected)) {
    detail =
      "Accounts show connected in UI but server tokens are missing — reconnect LinkedIn in Connected Accounts.";
  } else {
    detail =
      "No social accounts connected — open Connected Accounts → Connect LinkedIn (required for auto-post).";
  }

  return { merged, ready, blockReasons, detail };
}
