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 { listProperties } from "@/lib/appwrite/property-queries";
import {
  DATABASE_ID,
  TABLES,
  type PropertyMatch,
  type CustomerSearch,
} from "@/lib/appwrite/schema";
import { createAdminClient } from "@/lib/appwrite/server";
import { MatchesClient } from "@/components/matches/matches-client";

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

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

  const matches = (
    JSON.parse(JSON.stringify(matchesResult.rows)) as PropertyMatch[]
  ).sort((a, b) => (b.score ?? 0) - (a.score ?? 0));

  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">
      <MatchesClient
        matches={matches}
        customers={customers}
        properties={properties}
        searches={searches}
      />
    </div>
  );
}
