export const dynamic = "force-dynamic";

import type { Metadata } from "next";
import { redirect } from "next/navigation";

import { getLogoUrl } from "@/lib/appwrite/storage";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { LogoUploader } from "./components/logo-uploader";
import { WorkspaceSettingsForm } from "./components/workspace-form";

export const metadata: Metadata = {
  title: "KovakEmlak — Ofis bilgileri",
};

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

  if (ctx.role === "member") redirect("/dashboard");

  const canEdit = ctx.role === "owner";
  const officeName = ctx.settings?.officeName ?? "Ofis";

  return (
    <div className="flex-1 space-y-6 px-6 pt-4">
      <div className="flex flex-col gap-1">
        <p className="text-muted-foreground text-sm">{officeName}</p>
        <h1 className="text-2xl font-bold tracking-tight">Ofis Bilgileri</h1>
        <p className="text-muted-foreground text-sm">
          Panel başlığında görünecek ofis bilgileri.
          {!canEdit && " Düzenlemek için yönetici yetkisine ihtiyacınız var."}
        </p>
      </div>

      <LogoUploader
        canEdit={canEdit}
        currentLogoUrl={getLogoUrl(ctx.settings?.logo)}
        companyName={officeName}
      />

      <WorkspaceSettingsForm
        canEdit={canEdit}
        defaults={{
          officeName: ctx.settings?.officeName ?? "",
          phone: ctx.settings?.phone ?? "",
          email: ctx.settings?.email ?? "",
          address: ctx.settings?.address ?? "",
          defaultCurrency: ctx.settings?.defaultCurrency ?? "TRY",
        }}
      />
    </div>
  );
}
