import { notFound } from "next/navigation";
import { requireAccount } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { AutomationEditor } from "@/components/automations/automation-editor";

export const dynamic = "force-dynamic";

export default async function EditAutomationPage({ params }: { params: Promise<{ id: string }> }) {
  const membership = await requireAccount();
  const accountId = membership.account.id;
  const { id } = await params;

  const [automation, tags, templates] = await Promise.all([
    prisma.automation.findUnique({
      where: { id, accountId },
      include: { 
        steps: { orderBy: { position: "asc" } },
        logs: { orderBy: { createdAt: "desc" }, take: 10 }
      }
    }),
    prisma.tag.findMany({ where: { accountId }, orderBy: { name: "asc" } }),
    prisma.messageTemplate.findMany({ where: { accountId }, orderBy: { name: "asc" } }),
  ]);

  if (!automation) return notFound();

  const formattedAutomation = {
    ...automation,
    runs: automation.logs.map((log: any) => ({
      id: log.id,
      status: log.status,
      startedAt: log.createdAt,
    }))
  };

  return <AutomationEditor automation={formattedAutomation} tags={tags} templates={templates} />;
}
