/**
 * Meta Page publishing scopes — must match permissions enabled on your Meta app
 * (use case: "Manage everything on your Page").
 * @see https://developers.facebook.com/docs/pages-api/getting-started/
 */

/** Bundled with the Page use case; required for /me/accounts and publishing. */
export const META_FACEBOOK_PAGE_SCOPES = [
  "public_profile",
  "business_management",
  "pages_show_list",
  "pages_manage_posts",
  "pages_manage_metadata",
  "pages_read_engagement",
] as const;

/** Instagram Business publishing via linked Facebook Page. */
export const META_INSTAGRAM_SCOPES = [
  "public_profile",
  "business_management",
  "pages_show_list",
  "pages_read_engagement",
  "instagram_basic",
  "instagram_content_publish",
] as const;

/** Deprecated — never request (OAuth will fail in Live mode). */
export const META_DEPRECATED_SCOPES = ["manage_pages", "publish_pages", "read_insights"] as const;

export interface MetaScopeValidation {
  valid: boolean;
  platform: "facebook" | "instagram";
  scopes: string[];
  missingRequired: string[];
  deprecatedRequested: string[];
  portalHint: string;
}

function parseScopes(raw: string | undefined): string[] {
  if (!raw?.trim()) return [];
  return raw
    .split(/[,\s]+/)
    .map((s) => s.trim())
    .filter(Boolean);
}

function requiredForFacebook(scopes: string[]): string[] {
  const missing: string[] = [];
  if (!scopes.includes("pages_show_list")) missing.push("pages_show_list");
  if (!scopes.includes("pages_manage_posts")) missing.push("pages_manage_posts");
  if (!scopes.includes("business_management")) missing.push("business_management");
  return missing;
}

function requiredForInstagram(scopes: string[]): string[] {
  const missing: string[] = [];
  if (!scopes.includes("pages_show_list")) missing.push("pages_show_list");
  if (!scopes.includes("instagram_basic")) missing.push("instagram_basic");
  if (!scopes.includes("instagram_content_publish")) missing.push("instagram_content_publish");
  if (!scopes.includes("business_management")) missing.push("business_management");
  return missing;
}

export function resolveMetaScopes(
  platform: "facebook" | "instagram",
  envFacebook?: string,
  envInstagram?: string,
): string[] {
  if (platform === "facebook") {
    const custom = parseScopes(envFacebook);
    return custom.length ? custom : [...META_FACEBOOK_PAGE_SCOPES];
  }
  const custom = parseScopes(envInstagram);
  return custom.length ? custom : [...META_INSTAGRAM_SCOPES];
}

export function validateMetaScopes(
  platform: "facebook" | "instagram",
  scopes: string[],
): MetaScopeValidation {
  const deprecatedRequested = scopes.filter((s) =>
    (META_DEPRECATED_SCOPES as readonly string[]).includes(s),
  );
  const missingRequired =
    platform === "facebook" ? requiredForFacebook(scopes) : requiredForInstagram(scopes);

  const portalHint =
    "Meta Developer Portal → add use case \"Manage everything on your Page\", " +
    "enable Facebook Login for Business, whitelist your redirect URI, then request " +
    "pages_manage_posts and pages_show_list under App Review (Advanced Access for Live mode).";

  return {
    valid: missingRequired.length === 0 && deprecatedRequested.length === 0,
    platform,
    scopes,
    missingRequired,
    deprecatedRequested,
    portalHint,
  };
}

export function metaScopesErrorMessage(validation: MetaScopeValidation): string {
  if (validation.valid) return "";

  const parts: string[] = [];
  if (validation.missingRequired.length) {
    parts.push(`Missing required scopes: ${validation.missingRequired.join(", ")}.`);
  }
  if (validation.deprecatedRequested.length) {
    parts.push(
      `Remove deprecated scopes: ${validation.deprecatedRequested.join(", ")}.`,
    );
  }
  parts.push(validation.portalHint);
  return parts.join(" ");
}

/** Shown when Meta OAuth dialog returns "Invalid Scopes" for pages_* permissions. */
export function metaInvalidScopesUserMessage(scopes?: string[]): string {
  const scopeList = scopes?.length
    ? scopes.join(", ")
    : "business_management, pages_show_list, pages_manage_posts, pages_manage_metadata, pages_read_engagement";

  return (
    `Meta rejected Page permissions (${scopeList}). ` +
    "Your Meta app only has basic Facebook Login — it does not include the " +
    '"Manage everything on your Page" use case yet. ' +
    "Fix this in Meta Developer Portal (developers.facebook.com), not in PostSync Pro code."
  );
}

export const META_PORTAL_SETUP_STEPS = [
  'Create or edit app → add use case: "Manage everything on your Page"',
  "Facebook Login for Business → Settings → enable Web OAuth Login",
  "Add Valid OAuth Redirect URI: https://postsyncpro.gventure.info/connected-accounts/oauth/facebook/callback",
  "App Roles: add your Facebook account as Admin/Developer (for Development mode testing)",
  "After setup, pages_show_list and pages_manage_posts appear in App Review → Permissions",
] as const;
