import { requireAccount } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { InboxClient } from "@/components/inbox/inbox-client";

export const dynamic = "force-dynamic";

export default async function InboxPage() {
  const membership = await requireAccount();
  const accountId = membership.account.id;

  try {
    const [conversations, members, waConfigured, templates, products, tags] = await Promise.all([
      prisma.conversation.findMany({
        where: { accountId },
        orderBy: { lastMessageAt: "desc" },
        take: 100,
        include: {
          contact: true,
          assignee: { select: { id: true, name: true } },
          messages: { orderBy: { createdAt: "desc" }, take: 1 },
        },
      }),
      prisma.accountMember.findMany({
        where: { accountId },
        include: { user: { select: { id: true, name: true } } },
      }),
      prisma.whatsappConfig.count({ where: { accountId, active: true } }),
      prisma.messageTemplate.findMany({ where: { accountId, metaStatus: "APPROVED" }, orderBy: { name: "asc" } }),
      prisma.product.findMany({ where: { accountId }, orderBy: { name: "asc" } }),
      prisma.tag.findMany({ where: { accountId }, orderBy: { name: "asc" } }),
    ]);

    return (
      <InboxClient
        initialConversations={conversations}
        members={members}
        whatsappConfigured={waConfigured > 0}
        templates={templates}
        products={products.map((p) => ({ ...p, price: Number(p.price) }))}
        allTags={tags}
      />
    );
  } catch (err: any) {
    if (err.message && err.message.includes('NEXT_REDIRECT')) throw err;
    return (
      <div className="p-8 text-red-500">
        <h1 className="text-xl font-bold mb-4">Error loading inbox data</h1>
        <pre className="bg-red-50 p-4 rounded text-sm overflow-auto">
          {err.message || String(err)}
        </pre>
      </div>
    );
  }
}
