import { redirect } from "next/navigation";

import { ShellPage } from "@/components/page-templates";
import { TablePlaceholder } from "@/components/placeholders";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export default async function CampaignRecipientsPage({ params }: { params: Promise<{ campaignId: string }> }) {
  const { campaignId } = await params;
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const campaign = await prisma.broadcastCampaign.findFirst({
    where: { id: campaignId, tenantId: session.tenantId }
  });
  if (!campaign) {
    redirect("/campaigns?error=campaign_not_found");
  }

  const recipients = await prisma.campaignRecipient.findMany({
    where: { campaignId },
    include: { contact: true },
    orderBy: { createdAt: "asc" }
  });

  return (
    <ShellPage shell="admin" title="Campaign Recipients" description="Status per recipient dan failure reason.">
      <TablePlaceholder
        title="Recipient list"
        columns={["Contact", "Phone", "Status", "Attempt", "Retry At", "Failure reason", "Sent at"]}
        rows={recipients.map((recipient) => [
          recipient.contact?.fullName || "-",
          recipient.phoneNumber,
          recipient.sendStatus,
          recipient.sendAttempts,
          recipient.nextRetryAt ? new Date(recipient.nextRetryAt).toLocaleString() : "-",
          recipient.failureReason || "-",
          recipient.sentAt ? recipient.sentAt.toLocaleString() : "-"
        ])}
      />
    </ShellPage>
  );
}
