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

import {
  getFinancialReport,
  type ReportPeriod,
} from "@/lib/appwrite/finance-report-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { ReportClient } from "./components/report-client";

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

const ALLOWED: ReportPeriod[] = ["month", "quarter", "year", "all"];

export default async function ReportsPage({
  searchParams,
}: {
  searchParams: Promise<{ period?: string }>;
}) {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  const sp = await searchParams;
  const period: ReportPeriod = (ALLOWED as string[]).includes(sp.period ?? "")
    ? (sp.period as ReportPeriod)
    : "month";

  const data = await getFinancialReport(ctx.tenantId, period);

  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">Finansal rapor</h1>
        <p className="text-muted-foreground text-sm">
          İşletmenizin nakit pozisyonu, gelir/gider performansı ve borç yükünün tek bakışta özeti.
        </p>
      </div>

      <ReportClient data={data} />
    </div>
  );
}
