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

import { listCustomers } from "@/lib/appwrite/customer-queries";
import { listInvoices } from "@/lib/appwrite/invoice-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { InvoicesClient } from "./components/invoices-client";

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

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

  const [invoices, customers] = await Promise.all([
    listInvoices(ctx.tenantId),
    listCustomers(ctx.tenantId),
  ]);

  const customerMap = new Map(customers.map((c) => [c.$id, c.name]));

  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">Faturalar</h1>
        <p className="text-muted-foreground text-sm">
          Müşterilerinize fatura kesin, kalemleri yönetin, durumu takip edin.
        </p>
      </div>

      <InvoicesClient
        invoices={invoices.map((i) => ({
          id: i.$id,
          number: i.number,
          customerId: i.customerId,
          customerName: customerMap.get(i.customerId) ?? "—",
          issueDate: i.issueDate,
          dueDate: i.dueDate,
          status: i.status ?? "draft",
          subtotal: i.subtotal ?? 0,
          vatTotal: i.vatTotal ?? 0,
          total: i.total ?? 0,
          notes: i.notes ?? "",
        }))}
        customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
      />
    </div>
  );
}
