// Shared types and helpers for normalizing API responses.

export type Devotional = {
  id?: string;
  scripture_reference: string;
  context?: string;
  text: string;
  topics: string[];
  prayer?: string;
  reflection?: string;
  date?: string;
  bookOrder?: number;
};

export const FALLBACK_TODAY: Devotional = {
  scripture_reference: "Psalm 119:105",
  context: "Psalm 119:105",
  text: "God's Word gives direction when the path ahead feels unclear. As you open Scripture today, let it light the next faithful step — not the whole road, just enough to move forward in trust.",
  topics: ["God's Word", "Guidance", "Trust God"],
  prayer:
    "Lord, guide my steps today through Your Word. Help me trust Your wisdom more than my own understanding. Amen.",
  reflection:
    "What decision or situation do I need to bring under the guidance of God's Word today?",
};

function pickString(...vals: unknown[]): string {
  for (const v of vals) if (typeof v === "string" && v.trim()) return v.trim();
  return "";
}

function pickArray(val: unknown): string[] {
  if (Array.isArray(val))
    return val.map((v) => (typeof v === "string" ? v : String(v ?? ""))).filter(Boolean);
  return [];
}

// Normalize one item from the Uncovered Treasure API into our shape.
export function normalizeOne(raw: unknown): Devotional {
  if (!raw || typeof raw !== "object") return { ...FALLBACK_TODAY };
  const r = raw as Record<string, unknown>;
  const scriptures = pickArray(r.scriptures);
  const context = pickString(r.context);
  const ref = pickString(
    r.scripture_reference,
    r.reference,
    context,
    scriptures[0],
    r.verse
  );
  return {
    id: typeof r.id === "string" ? r.id : undefined,
    scripture_reference: ref || "Scripture",
    context: context || ref || undefined,
    text: pickString(r.text, r.devotional, r.insight, r.body, r.content),
    topics: pickArray(r.topics),
    date: typeof r.date === "string" ? r.date : undefined,
    bookOrder: typeof r.bookOrder === "number" ? r.bookOrder : undefined,
  };
}

export function normalizeList(payload: unknown): Devotional[] {
  if (!payload) return [];
  const p = payload as Record<string, unknown>;
  const arr = Array.isArray(p.results)
    ? p.results
    : Array.isArray(payload)
      ? (payload as unknown[])
      : [];
  return arr.map(normalizeOne).filter((d) => d.text);
}

export function normalizeToday(payload: unknown): Devotional {
  const list = normalizeList(payload);
  if (list.length > 0) {
    return { ...FALLBACK_TODAY, ...list[0], topics: list[0].topics.length ? list[0].topics : FALLBACK_TODAY.topics };
  }
  // try single-object shape
  const single = normalizeOne(payload);
  if (single.text) return { ...FALLBACK_TODAY, ...single };
  return FALLBACK_TODAY;
}

export function extractTopics(payload: unknown): string[] {
  if (!payload) return [];
  const p = payload as Record<string, unknown>;
  if (Array.isArray(p.topics)) return p.topics.map((t) => String(t)).filter(Boolean);
  if (Array.isArray(p.results)) return p.results.map((t) => String(t)).filter(Boolean);
  if (Array.isArray(payload)) return (payload as unknown[]).map((t) => String(t)).filter(Boolean);
  return [];
}

export const FEATURED_TOPICS = [
  "Prayer",
  "Faith",
  "Fear",
  "Forgiveness",
  "Love",
  "Hope",
  "Trust God",
  "Obedience",
  "Wisdom",
  "Repentance",
  "Spiritual Growth",
  "Worship",
];
