import GroupDetailClient from "@/components/annaulMazad/GroupDetailClient";
import {
  getGroupAuctionById,
  getAuctionGroupById,
  getGroupSingleAuctions,
} from "@/actions/group-auctions";
import { metaObject } from "@/config/site.config";
import { buildHorseFallbackGroupDetails } from "@/lib/annualAuctionGroups";
import { getLocale, getTranslations } from "next-intl/server";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ id: string; groupId: string; lang: string }>;
}) {
  const locale = await getLocale();
  const t = await getTranslations({
    locale,
    namespace: "GROUP_DETAIL_PAGE",
  });
  return metaObject(t("meta_title"), t("meta_description"));
}

type Props = {
  params: Promise<{ id: string; groupId: string; lang: string }>;
};

export default async function GroupDetailPage({ params }: Props) {
  const { id, groupId } = await params;

  let auction = null;
  let groupDetails = null;
  let initialItems: unknown[] = [];

  try {
    auction = await getGroupAuctionById(id);
  } catch (e) {
    console.error("Failed to fetch group auction:", e);
  }

  const isHorseFallbackGroup =
    groupId === id &&
    String((auction as { animal_type?: string } | null)?.animal_type || "").toLowerCase() ===
      "horse";

  if (!isHorseFallbackGroup) {
    try {
      groupDetails = await getAuctionGroupById(id, groupId);
      const nested =
        (groupDetails as any)?.single_auctions ?? (groupDetails as any)?.items;
      if (Array.isArray(nested)) initialItems = nested;
    } catch (e) {
      console.error("Failed to fetch auction group details:", e);
    }
  }

  if (initialItems.length === 0) {
    try {
      const res = isHorseFallbackGroup
        ? await getGroupSingleAuctions(id)
        : await getGroupSingleAuctions(id, undefined, groupId);
      const raw = (res as any)?.data?.data ?? (res as any)?.data ?? [];
      initialItems = Array.isArray(raw) ? raw : [];
    } catch {
      // ignore
    }
  }

  if (!groupDetails && auction && isHorseFallbackGroup) {
    groupDetails = buildHorseFallbackGroupDetails(auction, initialItems as any);
  }

  return (
    <GroupDetailClient
      auction={auction}
      groupDetails={groupDetails}
      groupAuctionId={id}
      auctionGroupId={groupId}
      initialItems={initialItems}
    />
  );
}
