import { MetadataRoute } from "next";
import axios from "axios";
import { fetchPublishedListingPropertyPageSlugs } from "@/utils/strapi";
import {
  getPrimaryTypeSlugForUrl,
  type PropertyTypePageRef,
} from "@/utils/propertyTypes";

const STRAPI_URL = process.env.NEXT_PUBLIC_STRAPI_URL;
const BASE_URL =
  process.env.NEXT_PUBLIC_BASE_URL ||
  process.env.NEXT_PUBLIC_SITE_URL ||
  (process.env.NODE_ENV === "production"
    ? "https://navana-realestate.com"
    : "http://localhost:3000");

interface PropertyRow {
  id: number;
  slug: string;
  updatedAt?: string;
  types?: PropertyTypePageRef[];
  propertyType?: string;
}

function normalizeTypesFromSitemap(item: any): PropertyTypePageRef[] {
  const raw = item.types ?? item.attributes?.types;
  const data = raw?.data;
  if (!data) return [];
  const arr = Array.isArray(data) ? data : [data];
  return arr
    .map((t: any) => {
      const a = t?.attributes ?? t;
      const slug = a?.slug ?? t?.slug;
      return typeof slug === "string" ? { slug } : null;
    })
    .filter((x): x is PropertyTypePageRef => x != null);
}

async function getAllProperties(): Promise<PropertyRow[]> {
  try {
    if (!STRAPI_URL) {
      console.warn("STRAPI_URL not set, skipping properties in sitemap");
      return [];
    }

    const response = await axios.get(
      `${STRAPI_URL}/api/properties?publicationState=live&pagination[limit]=1000&fields[0]=slug&fields[1]=propertyType&fields[2]=updatedAt&populate[types][fields][0]=slug`,
      { timeout: 10000 }
    );

    if (response?.data?.data) {
      return response.data.data.map((item: any) => {
        const a = item.attributes ?? item;
        const types = normalizeTypesFromSitemap(item);
        return {
          id: item.id,
          slug: a.slug || item.slug || "",
          propertyType: a.propertyType,
          types,
          updatedAt: a.updatedAt || item.updatedAt,
        };
      });
    }
    return [];
  } catch {
    return [];
  }
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const staticPages: MetadataRoute.Sitemap = [
    {
      url: BASE_URL,
      lastModified: new Date(),
      changeFrequency: "weekly",
      priority: 1.0,
    },
    {
      url: `${BASE_URL}/properties`,
      lastModified: new Date(),
      changeFrequency: "weekly",
      priority: 0.9,
    },
    {
      url: `${BASE_URL}/contact`,
      lastModified: new Date(),
      changeFrequency: "monthly",
      priority: 0.8,
    },
    {
      url: `${BASE_URL}/the-brand`,
      lastModified: new Date(),
      changeFrequency: "monthly",
      priority: 0.8,
    },
    {
      url: `${BASE_URL}/news`,
      lastModified: new Date(),
      changeFrequency: "weekly",
      priority: 0.7,
    },
    {
      url: `${BASE_URL}/designo`,
      lastModified: new Date(),
      changeFrequency: "monthly",
      priority: 0.7,
    },
    {
      url: `${BASE_URL}/fmd`,
      lastModified: new Date(),
      changeFrequency: "monthly",
      priority: 0.7,
    },
    {
      url: `${BASE_URL}/search`,
      lastModified: new Date(),
      changeFrequency: "weekly",
      priority: 0.6,
    },
  ];

  const listingSlugs = await fetchPublishedListingPropertyPageSlugs();
  const propertyTypePages: MetadataRoute.Sitemap =
    listingSlugs.length > 0
      ? listingSlugs.map((slug) => ({
          url: `${BASE_URL}/properties/${slug}`,
          lastModified: new Date(),
          changeFrequency: "weekly",
          priority: 0.9,
        }))
      : ["residential", "commercial", "condominium", "land"].map((slug) => ({
          url: `${BASE_URL}/properties/${slug}`,
          lastModified: new Date(),
          changeFrequency: "weekly",
          priority: 0.9,
        }));

  const properties = await getAllProperties();
  const propertyPages: MetadataRoute.Sitemap = properties.map((property) => ({
    url: `${BASE_URL}/properties/${getPrimaryTypeSlugForUrl(property)}/${property.slug}`,
    lastModified: property.updatedAt
      ? new Date(property.updatedAt)
      : new Date(),
    changeFrequency: "monthly" as const,
    priority: 0.8,
  }));

  return [...staticPages, ...propertyTypePages, ...propertyPages];
}
