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

import { listCustomers } from "@/lib/appwrite/customer-queries";
import { listAssignments, listSoftware } from "@/lib/appwrite/software-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { SoftwareClient } from "./components/software-client";

export const metadata: Metadata = {
  title: "İşletmem — Yazılımlarımız",
};

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

  const [softwareList, customers, assignments] = await Promise.all([
    listSoftware(ctx.tenantId),
    listCustomers(ctx.tenantId),
    listAssignments(ctx.tenantId),
  ]);

  const softwareMap = new Map(softwareList.map((s) => [s.$id, s]));
  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">Yazılımlarımız</h1>
        <p className="text-muted-foreground text-sm">
          Yazılım kataloğunuzu yönetin ve müşterilere atayın.
        </p>
      </div>

      <SoftwareClient
        software={softwareList.map((s) => ({
          id: s.$id,
          name: s.name,
          version: s.version ?? "",
          description: s.description ?? "",
          defaultFee: s.defaultFee ?? null,
        }))}
        assignments={assignments.map((a) => ({
          id: a.$id,
          customerId: a.customerId,
          customerName: customerMap.get(a.customerId) ?? "—",
          softwareId: a.softwareId,
          softwareName: softwareMap.get(a.softwareId)?.name ?? "—",
          softwareVersion: softwareMap.get(a.softwareId)?.version ?? "",
          startDate: a.startDate ?? "",
          endDate: a.endDate ?? "",
          fee: a.fee ?? null,
          billingPeriod: a.billingPeriod ?? "monthly",
          notes: a.notes ?? "",
        }))}
        customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
      />
    </div>
  );
}
