import { redirect } from "next/navigation";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { createSessionClient } from "@/lib/appwrite/server";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { MfaPanel } from "./components/mfa-panel";

export const metadata = {
  title: "DLS — Güvenlik",
};

export default async function SecurityPage() {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  // Look up the user's current MFA status straight from the session
  // client so the panel knows whether to offer enroll or disable.
  let mfaEnabled = false;
  try {
    const { account } = await createSessionClient();
    const user = await account.get();
    mfaEnabled = Boolean(user.mfa);
  } catch {
    // ignore — panel will treat as not enabled
  }

  return (
    <div className="flex-1 space-y-6 px-6">
      <div className="flex flex-col gap-1">
        <p className="text-muted-foreground text-sm">{ctx.settings?.companyName ?? "Çalışma alanı"}</p>
        <h1 className="text-2xl font-bold tracking-tight">Güvenlik</h1>
        <p className="text-muted-foreground text-sm">
          Hesap erişiminizi koruyan ayarlar. İki adımlı doğrulamayı açtığınızda
          giriş yaparken authenticator uygulamanızdaki 6 haneli kod istenir.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>İki Adımlı Doğrulama</CardTitle>
          <CardDescription>
            Authenticator uygulaması (Google Authenticator, 1Password, Authy, vs.)
            ile TOTP. SMS desteklenmiyor.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <MfaPanel initiallyEnabled={mfaEnabled} />
        </CardContent>
      </Card>
    </div>
  );
}
