export type LinkedInScopeMode = "openid" | "legacy" | "invalid";

export interface LinkedInScopeValidation {
  mode: LinkedInScopeMode;
  valid: boolean;
  hasPublish: boolean;
  hasProfile: boolean;
  raw: string;
  envExample: string;
  portalHint: string;
}

const OPENID_PROFILE = ["openid", "profile", "email"];
const LEGACY_PROFILE = ["r_liteprofile", "r_basicprofile"];

export function validateLinkedInScopes(scopesRaw?: string): LinkedInScopeValidation {
  const raw = scopesRaw?.trim() ?? "";
  const parts = raw.split(/\s+/).filter(Boolean);
  const hasPublish = parts.includes("w_member_social");
  const hasOpenId = parts.includes("openid");
  const hasLegacyProfile = LEGACY_PROFILE.some((s) => parts.includes(s));

  if (hasOpenId && hasPublish) {
    return {
      mode: "openid",
      valid: true,
      hasPublish: true,
      hasProfile: true,
      raw,
      envExample: "openid profile email w_member_social",
      portalHint:
        'LinkedIn Developer Portal → Products → add "Sign In with LinkedIn using OpenID Connect" and "Share on LinkedIn".',
    };
  }

  if (hasLegacyProfile && hasPublish) {
    return {
      mode: "legacy",
      valid: true,
      hasPublish: true,
      hasProfile: true,
      raw,
      envExample: "r_liteprofile r_emailaddress w_member_social",
      portalHint:
        'LinkedIn Developer Portal → Products → ensure "Sign In with LinkedIn" and "Share on LinkedIn" are enabled.',
    };
  }

  return {
    mode: "invalid",
    valid: false,
    hasPublish,
    hasProfile: hasOpenId || hasLegacyProfile,
    raw,
    envExample: "r_liteprofile r_emailaddress w_member_social",
    portalHint:
      "LINKEDIN_SCOPES must include w_member_social plus either openid profile email (OpenID) OR r_liteprofile (legacy).",
  };
}

export function linkedInScopesErrorMessage(validation: LinkedInScopeValidation): string {
  if (validation.valid) return "";

  return (
    "Invalid LINKEDIN_SCOPES. Use one of:\n" +
    "• OpenID (recommended): openid profile email w_member_social\n" +
    "• Legacy (your app lists r_liteprofile): r_liteprofile r_emailaddress w_member_social\n" +
    validation.portalHint
  );
}

export function linkedInReconnectHint(validation: LinkedInScopeValidation): string {
  if (validation.mode === "legacy") {
    return (
      `Set LINKEDIN_SCOPES=${validation.envExample} in .env.local, restart the app, disconnect and reconnect LinkedIn.`
    );
  }
  return (
    "Enable Sign In with LinkedIn using OpenID Connect in LinkedIn Developer Portal, " +
    "set LINKEDIN_SCOPES=openid profile email w_member_social, restart, then reconnect."
  );
}
