import { fetchBaserowRows } from "../lib/baserow";

export interface BannerItem {
  id: number;
  desktopImage: string;
  mobileImage: string;
  url?: string;
}

interface BaserowBannerRow {
  id: number;
  [key: string]: unknown;
  "Slide Number"?: string;
  Active?: boolean;
  "Image URL Desktop"?: string;
  "Image URL Mobile"?: string;
  "URL Banner"?: string;
}

export async function fetchBanners(): Promise<BannerItem[]> {
  const tableId = import.meta.env.BASEROW_BANNER_TABLE_ID;

  if (!tableId) {
    console.warn("BASEROW_BANNER_TABLE_ID not set — returning empty");
    return [];
  }

  try {
    const rows = await fetchBaserowRows<BaserowBannerRow>(tableId);

    return rows
      .filter(
        (row) =>
          row.Active !== false &&
          row["Image URL Desktop"] &&
          row["Image URL Mobile"],
      )
      .map((row) => ({
        id: row.id,
        desktopImage: row["Image URL Desktop"]!,
        mobileImage: row["Image URL Mobile"]!,
        url: row["URL Banner"] || undefined,
      }));
  } catch (e) {
    console.error("Failed to fetch banners from Baserow:", e);
    return [];
  }
}
