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

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

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

export default async function OnboardingPage() {
  const user = await getCurrentUser();
  if (!user) redirect("/sign-in");

  // Use admin client — never fails due to expired session tokens.
  // If user already has a team with CRM settings, send them to dashboard.
  try {
    const { users, tablesDB } = createAdminClient();
    const memberships = await users.listMemberships(user.$id);
    if (memberships.total > 0) {
      const teamIds = memberships.memberships.map((m) => m.teamId);
      const settings = await tablesDB.listRows({
        databaseId: DATABASE_ID,
        tableId: TABLES.tenantSettings,
        queries: [Query.equal("tenantId", teamIds), Query.limit(1)],
      });
      if (settings.rows.length > 0) redirect("/dashboard");
    }
  } catch {
    // Admin client uses an API key (not a session), so this is extremely rare.
    // If it does fail, show a 500 rather than silently letting the user create
    // a duplicate workspace.
    throw new Error("Onboarding guard check failed — server configuration issue.");
  }

  const crossAppTeams = await getCrossAppTeams();

  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}
        />
      </div>
    </div>
  );
}
