import { connectDB } from "@/lib/db";
import { DocumentTemplate } from "@/models/DocumentTemplate";
import { GeneratedDocument } from "@/models/GeneratedDocument";
import { Client } from "@/models/Client";
import { Department } from "@/models/Department";
import { Position } from "@/models/Position";
import { DOCUMENT_CATEGORIES, documentCategoryPermission, type DocumentCategory } from "@/lib/documentConstants";
import { hasPermission } from "@/lib/adminAuth";
import { formatDateDE, formatEUR } from "@/lib/orderConstants";

// Platzhalter-Autofill aus dem Mitarbeiterprofil (25.09.2026 nachgezogen) -
// selbe Berechnung wie admin/documents/page.tsx (clientOptions), damit die
// Team-API dieselben automatisch ausgefüllten Felder liefert wie die
// Web-Oberfläche, statt sie dort zu duplizieren.
export async function getDocumentsData() {
  const visibleCategories: DocumentCategory[] = [];
  for (const cat of DOCUMENT_CATEGORIES) {
    if (await hasPermission(documentCategoryPermission(cat, "view"))) visibleCategories.push(cat);
  }
  if (visibleCategories.length === 0) return null;

  await connectDB();
  const [templatesAll, generatedAll, staff, departments, positions] = await Promise.all([
    DocumentTemplate.find({ category: { $in: visibleCategories } }).sort({ sortOrder: 1 }).lean(),
    GeneratedDocument.find({ category: { $in: visibleCategories } }).sort({ createdAt: -1 }).limit(200).lean(),
    Client.find({ role: "staff" }).sort({ name: 1 }).lean(),
    Department.find({}).lean(),
    Position.find({}).lean(),
  ]);
  const departmentById = new Map(departments.map((d) => [String(d._id), d]));
  const positionById = new Map(positions.map((p) => [String(p._id), p]));

  return {
    visibleCategories,
    templates: templatesAll.map((t) => ({
      _id: String(t._id),
      name: t.name,
      category: t.category,
      body: t.body,
      defaultIncludeLetterhead: t.defaultIncludeLetterhead,
      defaultIncludeFooter: t.defaultIncludeFooter,
      defaultFooterText: t.defaultFooterText,
      defaultIncludeRecipientAddress: t.defaultIncludeRecipientAddress,
    })),
    generated: generatedAll.map((g) => ({
      _id: String(g._id),
      templateName: g.templateName,
      category: g.category,
      clientName: g.clientName,
      renderedBody: g.renderedBody,
      includeLetterhead: g.includeLetterhead,
      includeFooter: g.includeFooter,
      footerText: g.footerText,
      includeRecipientAddress: g.includeRecipientAddress,
      recipientAddress: g.recipientAddress,
      createdAt: new Date(g.createdAt).toISOString(),
      signature: g.signature ? { name: g.signature.name, signedAt: new Date(g.signature.signedAt).toISOString(), ip: g.signature.ip } : null,
    })),
    staff: staff.map((c) => ({
      _id: String(c._id),
      name: c.name,
      departmentName: c.departmentId ? departmentById.get(String(c.departmentId))?.name ?? "" : "",
      positionName: c.positionId ? positionById.get(String(c.positionId))?.name ?? "" : "",
      address: c.address || "",
      employmentStartDate: (() => {
        const dates = (c.employmentRecords || []).map((r) => new Date(r.startDate).getTime());
        return dates.length ? formatDateDE(new Date(Math.min(...dates))) : "";
      })(),
      birthDate: c.birthDate ? formatDateDE(new Date(c.birthDate)) : "",
      probezeit: (() => {
        const records = c.employmentRecords || [];
        const months = records[records.length - 1]?.probationMonths;
        return months ? `${months} ${months === 1 ? "Monat" : "Monate"}` : "";
      })(),
      stundenlohn: (() => {
        const position = c.positionId ? positionById.get(String(c.positionId)) : null;
        const department = c.departmentId ? departmentById.get(String(c.departmentId)) : null;
        const wage = c.hourlyWage ?? position?.defaultHourlyWage ?? department?.defaultHourlyWage ?? null;
        return wage != null ? `${wage.toLocaleString("de-DE")} €` : "";
      })(),
      gehalt: (() => {
        const position = c.positionId ? positionById.get(String(c.positionId)) : null;
        const department = c.departmentId ? departmentById.get(String(c.departmentId)) : null;
        const wage = c.hourlyWage ?? position?.defaultHourlyWage ?? department?.defaultHourlyWage ?? null;
        return wage != null && c.monthlyHours != null ? formatEUR(Math.round(wage * c.monthlyHours * 100) / 100) : "";
      })(),
      urlaubstage: c.vacationDaysPerYear != null ? `${c.vacationDaysPerYear} Tage` : "",
    })),
  };
}
