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

import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { WorkspaceSettingsForm } from "./components/workspace-form";

export const metadata: Metadata = {
  title: "İşletmem — Şirket bilgileri",
};

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

  const canEdit = ctx.role === "owner" || ctx.role === "admin";

  return (
    <div className="flex-1 space-y-6 px-6 pt-0">
      <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">Şirket bilgileri</h1>
        <p className="text-muted-foreground text-sm">
          Faturalarda ve panel başlığında görünecek şirket bilgileri.
          {!canEdit && " Düzenlemek için yönetici yetkisine ihtiyacınız var."}
        </p>
      </div>

      <WorkspaceSettingsForm
        canEdit={canEdit}
        defaults={{
          companyName: ctx.settings?.companyName ?? "",
          companyTaxId: ctx.settings?.companyTaxId ?? "",
          companyAddress: ctx.settings?.companyAddress ?? "",
          companyEmail: ctx.settings?.companyEmail ?? "",
          companyPhone: ctx.settings?.companyPhone ?? "",
          defaultVatRate:
            typeof ctx.settings?.defaultVatRate === "number"
              ? ctx.settings.defaultVatRate
              : 20,
          invoicePrefix: ctx.settings?.invoicePrefix ?? "INV",
          invoiceCounter: ctx.settings?.invoiceCounter ?? 0,
        }}
      />
    </div>
  );
}
