import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { Order } from "@/models/Order";

// Extrahiert aus admin/clients/page.tsx — von dort UND von der Team-App-API
// (api/team/v1/clients) genutzt.
const PAGE_SIZE = 25;

function escapeRegex(s: string) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

export type ClientRow = {
  _id: string;
  name: string;
  firstName: string;
  email: string;
  avatarPath: string;
  tags: string[];
  verified: boolean;
  deletionRequestedAt: string | null;
  orderCount: number;
  birthDate: string | null;
};

export async function getClientList(params: { q?: string; page?: number }) {
  const { q = "", page: pageParam = 1 } = params;
  const page = Math.max(1, pageParam || 1);

  await connectDB();

  const filter: Record<string, unknown> = { role: "client" };
  if (q.trim()) {
    const rx = new RegExp(escapeRegex(q.trim()), "i");
    filter.$or = [
      { name: rx },
      { email: rx },
      { nickname: rx },
      { tags: rx },
      // Geburtsdatum als DD.MM.YYYY-Text durchsuchbar (z. B. "12.05" oder
      // "2000") — Nutzer-Wunsch, um Kunden auch übers Geburtsdatum zu finden.
      {
        $expr: {
          $regexMatch: {
            input: { $dateToString: { format: "%d.%m.%Y", date: "$birthDate", onNull: "" } },
            regex: escapeRegex(q.trim()),
            options: "i",
          },
        },
      },
    ];
  }

  const [rawClients, total] = await Promise.all([
    Client.find(filter).sort({ name: 1 }).skip((page - 1) * PAGE_SIZE).limit(PAGE_SIZE).lean(),
    Client.countDocuments(filter),
  ]);

  const orderCounts = await Order.aggregate([
    { $match: { clientId: { $in: rawClients.map((c) => c._id) } } },
    { $group: { _id: "$clientId", count: { $sum: 1 } } },
  ]);
  const orderCountByClientId = new Map(orderCounts.map((o) => [String(o._id), o.count]));

  const clients: ClientRow[] = rawClients.map((c) => ({
    _id: String(c._id),
    name: c.name,
    firstName: c.firstName || "",
    email: c.email,
    avatarPath: c.avatarPath || "",
    tags: c.tags || [],
    verified: c.verified,
    deletionRequestedAt: c.deletionRequestedAt ? new Date(c.deletionRequestedAt).toISOString() : null,
    orderCount: orderCountByClientId.get(String(c._id)) ?? 0,
    birthDate: c.birthDate ? new Date(c.birthDate).toISOString() : null,
  }));

  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
  return { clients, total, totalPages, page };
}
