import { createClient } from "@/lib/supabase/server";
import { PageHeader } from "@/components/layout/page-header";
import { canDo } from "@/lib/auth/permissions";
import type { PromotionalMaterial } from "@/lib/types";
import { MaterialsClient, type MaterialWithUrl } from "./materials-client";

export default async function PromotionalMaterialsPage() {
  const supabase = await createClient();

  const { data } = await supabase
    .from("promotional_materials")
    .select("*")
    .order("created_at", { ascending: false });

  const materials = (data ?? []) as PromotionalMaterial[];

  const withUrls: MaterialWithUrl[] = await Promise.all(
    materials.map(async (m) => {
      if (!m.file_path) return { ...m, signedUrl: null };
      const { data: signed } = await supabase.storage
        .from("marketing")
        .createSignedUrl(m.file_path, 3600);
      return { ...m, signedUrl: signed?.signedUrl ?? null };
    }),
  );

  const cats = Array.from(
    new Set(
      materials
        .map((m) => m.category?.trim())
        .filter((c): c is string => Boolean(c)),
    ),
  ).sort((a, b) => a.localeCompare(b));

  return (
    <div>
      <PageHeader
        title="Promotional Materials"
        breadcrumb="Home / Promotional Materials"
      />
      <MaterialsClient
        materials={withUrls}
        categories={cats}
        canManage={await canDo("promotional", "update")}
      />
    </div>
  );
}
