export const dynamic = "force-dynamic";

import type { Metadata } from "next";
import { redirect } from "next/navigation";
import Link from "next/link";
import { ArrowLeft } from "@/lib/icons";

import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { getPaymentHistoryAction } from "@/lib/appwrite/subscription-actions";
import { PaymentHistory } from "../components/payment-history";

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

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

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

  const events = await getPaymentHistoryAction();
  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">
        <Link
          href="/settings/billing"
          className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors w-fit mb-1"
        >
          <ArrowLeft className="h-3.5 w-3.5" />
          Plan & Faturalama
        </Link>
        <p className="text-muted-foreground text-sm">{officeName}</p>
        <h1 className="text-2xl font-bold tracking-tight">Faturalar</h1>
        <p className="text-muted-foreground text-sm">
          Abonelik ödemelerinizin geçmişi.
        </p>
      </div>

      <PaymentHistory events={events} />
    </div>
  );
}
