import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { createAdminClient } from "@/lib/appwrite/server";
import { DATABASE_ID, TABLES } from "@/lib/appwrite/schema";
import { listCustomers } from "@/lib/appwrite/customer-queries";
import { Query } from "node-appwrite";
import { FinanceClient } from "@/components/finance/finance-client";
import type { Deal } from "@/lib/appwrite/schema";

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

  const dealQueries = [
    Query.equal("tenantId", ctx.tenantId),
    Query.orderDesc("$createdAt"),
    Query.limit(200),
  ];

  if (ctx.role === "member") {
    dealQueries.push(Query.equal("agentId", ctx.user.id));
  }

  const [dealsResult, customers] = await Promise.all([
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.deals,
      queries: dealQueries,
    }),
    listCustomers(ctx.tenantId),
  ]);

  const deals = JSON.parse(JSON.stringify(dealsResult.rows)) as Deal[];

  return (
    <div className="px-4 md:px-6 lg:px-8">
      <FinanceClient
        initialDeals={deals}
        customers={customers}
        role={ctx.role}
        userId={ctx.user.id}
        userName={ctx.user.name}
      />
    </div>
  );
}
