export const dynamic = "force-dynamic";

import { notFound } from "next/navigation";
import { Query } from "node-appwrite";

import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { listCustomers } from "@/lib/appwrite/customer-queries";
import {
  DATABASE_ID,
  TABLES,
  type Property,
  type PropertyMatch,
  type CustomerSearch,
  type Activity,
} from "@/lib/appwrite/schema";
import { createAdminClient } from "@/lib/appwrite/server";
import { parseImageIds } from "@/lib/appwrite/storage-utils";
import { PropertyDetailClient } from "@/components/properties/property-detail-client";

interface Props {
  params: Promise<{ id: string }>;
}

export default async function PropertyDetailPage({ params }: Props) {
  const { id } = await params;
  const ctx = await requireTenant();
  const { tablesDB } = createAdminClient();

  let property: Property;
  try {
    const row = await tablesDB.getRow(DATABASE_ID, TABLES.properties, id);
    property = JSON.parse(JSON.stringify(row)) as Property;
  } catch {
    notFound();
  }

  if (property.tenantId !== ctx.tenantId) notFound();

  const [customers, matchesResult, activitiesResult, searchesResult] = await Promise.all([
    listCustomers(ctx.tenantId),
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.propertyMatches,
      queries: [
        Query.equal("propertyId", id),
        Query.equal("tenantId", ctx.tenantId),
        Query.orderDesc("score"),
        Query.limit(50),
      ],
    }),
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.activities,
      queries: [
        Query.equal("propertyId", id),
        Query.equal("tenantId", ctx.tenantId),
        Query.orderDesc("$createdAt"),
        Query.limit(20),
      ],
    }),
    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[];
  const activities = JSON.parse(JSON.stringify(activitiesResult.rows)) as Activity[];
  const searches = JSON.parse(JSON.stringify(searchesResult.rows)) as CustomerSearch[];
  const imageIds = parseImageIds(property.imageIds);

  return (
    <PropertyDetailClient
      property={property}
      matches={matches}
      activities={activities}
      imageIds={imageIds}
      customers={customers}
      searches={searches}
    />
  );
}
