/**
 * Property listing pages in Strapi (collection: types ↔ Property.types).
 * URL segment /properties/[slug]/... uses a listing page slug (often residential, commercial, …).
 */

export interface PropertyTypePageRef {
  slug: string;
  name?: string;
}

export function normalizeTypesFromStrapi(raw: unknown): PropertyTypePageRef[] {
  if (raw == null) return [];
  const unwrap = (entry: unknown): PropertyTypePageRef | null => {
    if (!entry || typeof entry !== "object") return null;
    const e = entry as Record<string, unknown>;
    const a = (e.attributes as Record<string, unknown> | undefined) ?? e;
    const slug = (a.slug ?? e.slug) as string | undefined;
    if (!slug || typeof slug !== "string") return null;
    const name = (a.name ?? e.name) as string | undefined;
    return name ? { slug, name } : { slug };
  };
  if (Array.isArray(raw)) {
    return raw.map(unwrap).filter(Boolean) as PropertyTypePageRef[];
  }
  const data = (raw as { data?: unknown }).data;
  if (data == null) return [];
  const arr = Array.isArray(data) ? data : [data];
  return arr.map(unwrap).filter(Boolean) as PropertyTypePageRef[];
}

/** Pick a single slug for /properties/{slug}/{propertySlug} links. */
export function getPrimaryTypeSlugForUrl(
  property: { types?: PropertyTypePageRef[]; propertyType?: string | null },
  preferredSlug?: string
): string {
  const slugs = property.types?.map((t) => t.slug).filter(Boolean) ?? [];
  const pref = preferredSlug?.toLowerCase();
  if (pref && slugs.some((s) => s.toLowerCase() === pref)) {
    return slugs.find((s) => s.toLowerCase() === pref) ?? pref;
  }
  if (slugs.length > 0) return slugs[0]!;
  const legacy = property.propertyType;
  if (legacy && typeof legacy === "string") return legacy;
  return "residential";
}

export function propertyMatchesListingSlug(
  property: { types?: PropertyTypePageRef[]; propertyType?: string | null },
  slug: string
): boolean {
  if (!slug || slug === "all") return true;
  const lower = slug.toLowerCase();
  if (property.types?.some((t) => t.slug?.toLowerCase() === lower)) return true;
  return (property.propertyType || "").toLowerCase() === lower;
}
