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

import { listBankAccounts } from "@/lib/appwrite/bank-account-queries";
import { listCustomers } from "@/lib/appwrite/customer-queries";
import { listFinanceEntries } from "@/lib/appwrite/finance-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { FinanceClient } from "./components/finance-client";

export const metadata: Metadata = {
  title: "İşletmem — Gelir / Gider",
};

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

  const [entries, customers, bankAccounts] = await Promise.all([
    listFinanceEntries(ctx.tenantId, ctx.user.id),
    listCustomers(ctx.tenantId),
    listBankAccounts(ctx.tenantId, ctx.user.id),
  ]);

  const customerMap = new Map(customers.map((c) => [c.$id, c.name]));
  const bankMap = new Map(
    bankAccounts.map((b) => [b.$id, `${b.bankName} — ${b.accountName}`]),
  );

  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">Gelir / Gider</h1>
        <p className="text-muted-foreground text-sm">
          Nakit hareketleri, borç ve alacaklarınızı tek yerden takip edin.
        </p>
      </div>

      <FinanceClient
        entries={entries.map((e) => ({
          id: e.$id,
          type: e.type,
          amount: e.amount,
          date: e.date,
          description: e.description ?? "",
          customerId: e.customerId ?? "",
          customerName: e.customerId ? customerMap.get(e.customerId) ?? "" : "",
          paymentMethod: e.paymentMethod ?? "",
          invoiceId: e.invoiceId ?? "",
          bankAccountId: e.bankAccountId ?? "",
          bankAccountLabel: e.bankAccountId ? bankMap.get(e.bankAccountId) ?? "" : "",
        }))}
        customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
        bankAccounts={bankAccounts
          .filter((b) => !b.archived)
          .map((b) => ({
            id: b.$id,
            label: `${b.bankName} — ${b.accountName}`,
          }))}
      />
    </div>
  );
}
