export const dynamic = "force-dynamic";

import { Query } from "node-appwrite";

import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { listCustomers } from "@/lib/appwrite/customer-queries";
import { DATABASE_ID, TABLES, type CustomerSearch } from "@/lib/appwrite/schema";
import { createAdminClient } from "@/lib/appwrite/server";
import { SearchesClient } from "@/components/customers/searches-client";

export default async function SearchesPage() {
  const ctx = await requireTenant();
  const { tablesDB } = createAdminClient();

  const [customers, searchesResult] = await Promise.all([
    listCustomers(ctx.tenantId),
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.customerSearches,
      queries: [
        Query.equal("tenantId", ctx.tenantId),
        Query.orderDesc("$createdAt"),
        Query.limit(500),
      ],
    }),
  ]);

  const searches = JSON.parse(JSON.stringify(searchesResult.rows)) as CustomerSearch[];

  return (
    <div className="flex flex-1 flex-col gap-4 p-4 md:p-6">
      <SearchesClient initialSearches={searches} customers={customers} />
    </div>
  );
}
