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

import {
  getBankAccountBalances,
  listBankAccounts,
} from "@/lib/appwrite/bank-account-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { BanksClient } from "./components/banks-client";

export const metadata: Metadata = {
  title: "İşletmem — Banka hesapları",
};

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

  const [accounts, balances] = await Promise.all([
    listBankAccounts(ctx.tenantId),
    getBankAccountBalances(ctx.tenantId),
  ]);

  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">Banka hesapları</h1>
        <p className="text-muted-foreground text-sm">
          İşletmenize ait banka hesaplarını ve güncel bakiyelerini takip edin.
        </p>
      </div>

      <BanksClient
        accounts={accounts.map((a) => ({
          id: a.$id,
          bankName: a.bankName,
          accountName: a.accountName,
          iban: a.iban ?? "",
          openingBalance: a.openingBalance ?? 0,
          notes: a.notes ?? "",
          archived: Boolean(a.archived),
          balance: balances.get(a.$id) ?? a.openingBalance ?? 0,
        }))}
      />
    </div>
  );
}
