import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { getAdminUser } from "@/lib/admin-permissions";
import { getCommunicationCampaigns } from "@/actions/communications/campaigns";
import { getCommunicationTemplates } from "@/actions/communications/templates";
import { getHarvestReachSegments } from "@/actions/harvest-reach/segments";
import { getCampaignAnalytics } from "@/actions/harvest-reach/campaigns";
import { listBrandsForAdmin } from "@/actions/brands";
import CommunicationsPage from "@/components/admin/CommunicationsPage";

export const metadata: Metadata = {
  title: "Harvest Reach - Communications Hub",
  description: "Manage email campaigns, templates, contacts, and marketing automation for your brand.",
};

export default async function CommunicationsRootPage() {
  const adminUser = await getAdminUser();
  if (!adminUser || !adminUser.can_manage_messages) {
    redirect("/admin/pickup");
  }

  // Resolve a real brand id. For platform_admin (and any other session
  // without an explicit brand), fall back to the first accessible brand
  // rather than a hard-coded UUID — the previous fallback was tied to
  // a specific DB and would FK-violate anywhere else, breaking the
  // "Create Template" / "New Campaign" forms with "violates foreign
  // key constraint email_templates_brand_id_fkey".
  let effectiveBrandId = adminUser!.brand_id ?? null;
  if (!effectiveBrandId) {
    const brands = await listBrandsForAdmin();
    effectiveBrandId = brands[0]?.id ?? null;
  }
  if (!effectiveBrandId) {
    // No brands exist — render the page with empty data rather than crash.
    return (
      <CommunicationsPage
        campaigns={[]}
        templates={[]}
        brandId=""
        initialSegments={[]}
        initialAnalytics={[]}
      />
    );
  }

  const [campaignsResult, templatesResult, segmentsResult, analyticsResult] = await Promise.all([
    getCommunicationCampaigns(effectiveBrandId),
    getCommunicationTemplates(effectiveBrandId),
    getHarvestReachSegments(effectiveBrandId),
    getCampaignAnalytics(effectiveBrandId),
  ]);

  return (
    <CommunicationsPage
      campaigns={campaignsResult.success ? campaignsResult.campaigns : []}
      templates={templatesResult.success ? templatesResult.templates : []}
      brandId={effectiveBrandId}
      initialSegments={segmentsResult.success ? segmentsResult.segments : []}
      initialAnalytics={analyticsResult}
    />
  );
}