import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import { getLinkedInConfig } from "@/lib/env";
import { ensureFreshAccountTokens } from "@/lib/social/ensure-publish-tokens";
import { probeLinkedInAccessToken } from "@/lib/social/linkedin-probe";
import { isLinkedInExternalIdValid } from "@/lib/social/linkedin-member";

/** LinkedIn connection diagnostics for debugging publish failures. */
export async function GET(request: Request) {
  const user = await getSessionUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const projectId = new URL(request.url).searchParams.get("projectId");
  if (!projectId) {
    return NextResponse.json({ error: "projectId query param is required" }, { status: 400 });
  }

  const { scopes, clientId, scopeValidation } = getLinkedInConfig();

  const accounts = await ensureFreshAccountTokens(user.id, projectId);
  const linkedin = accounts.find((a) => a.platform === "linkedin");

  if (!linkedin?.connected || !linkedin.accessToken) {
    return NextResponse.json({
      connected: false,
      scopeMode: scopeValidation.mode,
      scopesConfigured: scopeValidation,
      clientIdConfigured: Boolean(clientId),
      recommendation:
        "Connect LinkedIn in Connected Accounts. " +
        `Set LINKEDIN_SCOPES=${scopeValidation.envExample} in .env.local and restart first.`,
    });
  }

  const probe = await probeLinkedInAccessToken(linkedin.accessToken, linkedin.externalId);

  return NextResponse.json({
    connected: true,
    connectionStatus: linkedin.connectionStatus,
    profileName: linkedin.profileName,
    externalIdValid: isLinkedInExternalIdValid(linkedin.externalId),
    externalIdPreview: linkedin.externalId
      ? `${linkedin.externalId.slice(0, 4)}…${linkedin.externalId.slice(-4)}`
      : null,
    hasRefreshToken: Boolean(linkedin.refreshToken),
    expiresAt: linkedin.expiresAt,
    scopeMode: scopeValidation.mode,
    scopesConfigured: scopeValidation,
    scopesRaw: scopes,
    clientIdConfigured: Boolean(clientId),
    probe: {
      ok: probe.ok,
      memberIdResolved: Boolean(probe.memberId),
      attempts: probe.attempts,
      recommendation: probe.recommendation,
    },
    readyToPublish: probe.ok && linkedin.connectionStatus === "connected",
  });
}
