import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { Query } from "node-appwrite";

import { createAdminClient, getCurrentUser } from "@/lib/appwrite/server";
import { DATABASE_ID, TABLES, type TenantKind } from "@/lib/appwrite/schema";
import { getUserTeams, getCrossAppTeams } from "@/lib/appwrite/tenant";
import { CreateWorkspaceForm } from "./components/create-workspace-form";

export const metadata: Metadata = {
  title: "DLS — Çalışma alanı oluştur",
  description: "DLS için ilk çalışma alanınızı kurun.",
};

export default async function OnboardingPage({
  searchParams,
}: {
  searchParams: Promise<{ kind?: string }>;
}) {
  const user = await getCurrentUser();
  if (!user) redirect("/sign-in");

  // Already has a DLS tenant? Send to dashboard. Cross-app teams without a
  // tenant_settings row in `lab` still belong on onboarding.
  const teams = await getUserTeams();
  if (teams && teams.total > 0) {
    const { tablesDB } = createAdminClient();
    const existing = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.tenantSettings,
      queries: [
        Query.equal("tenantId", teams.teams.map((t) => t.$id)),
        Query.limit(1),
      ],
    });
    if (existing.total > 0) redirect("/dashboard");
  }

  const crossAppTeams = await getCrossAppTeams();

  const { kind: rawKind } = await searchParams;
  const initialKind: TenantKind | null =
    rawKind === "lab" || rawKind === "clinic" ? rawKind : null;

  return (
    <div className="bg-muted flex min-h-svh flex-col items-center justify-center p-6 md:p-10">
      <div className="w-full max-w-md">
        <CreateWorkspaceForm
          userName={user.name?.split(" ")[0]}
          crossAppTeams={crossAppTeams}
          initialKind={initialKind}
        />
      </div>
    </div>
  );
}
