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 Activity } from "@/lib/appwrite/schema";
import { createAdminClient } from "@/lib/appwrite/server";
import { ActivitiesClient } from "@/components/activities/activities-client";

export default async function ActivitiesPage() {
  const ctx = await requireTenant();
  const { tablesDB, teams, users } = createAdminClient();

  const [customers, properties, activitiesResult, membershipsResult] = await Promise.all([
    listCustomers(ctx.tenantId),
    listProperties(ctx.tenantId),
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.activities,
      queries: [
        Query.equal("tenantId", ctx.tenantId),
        Query.orderDesc("$createdAt"),
        Query.limit(300),
      ],
    }),
    teams.listMemberships(ctx.tenantId),
  ]);

  const activities = JSON.parse(JSON.stringify(activitiesResult.rows)) as Activity[];

  const members = (
    await Promise.all(
      membershipsResult.memberships
        .filter((m) => m.userId && m.confirm)
        .map(async (m) => {
          const u = await users.get(m.userId).catch(() => null);
          return u ? { id: m.userId, name: u.name } : null;
        }),
    )
  ).filter((m): m is { id: string; name: string } => m !== null);

  return (
    <div className="flex flex-1 flex-col gap-4 p-4 md:p-6">
      <ActivitiesClient
        initialActivities={activities}
        customers={customers}
        properties={properties}
        role={ctx.role}
        members={members}
        currentUserId={ctx.user.id}
      />
    </div>
  );
}
