import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { getSettings } from "@/lib/settings";
import { sendMail } from "@/lib/mail";
import { emailShell } from "@/lib/emailTemplate";
import { probationEndDate, PROBATION_ELIGIBLE_TYPES } from "@/lib/employment";
import { formatDateDE } from "@/lib/orderConstants";

const WARN_DAYS_AHEAD = 14;

// Täglicher Cron-Lauf (siehe api/cron/probation-reminder) — findet
// Personalakte-Einträge vom Typ "employee" oder "apprentice" mit gesetzter
// Probezeit, deren Ende in den nächsten 14 Tagen liegt, und erinnert Rakku
// einmalig pro Eintrag daran (kein automatischer Eingriff ins
// Arbeitsverhältnis, nur ein Hinweis rechtzeitig vor der Entscheidungsfrist).
export async function runProbationReminderSweep() {
  await connectDB();
  const settings = await getSettings();
  const adminEmail = settings.invoiceSettings?.email || settings.socialLinks?.email;
  if (!adminEmail) return { sent: 0, skipped: "no-admin-email" as const };

  const candidates = await Client.find({
    role: "staff",
    employmentRecords: {
      $elemMatch: { type: { $in: PROBATION_ELIGIBLE_TYPES }, probationMonths: { $ne: null }, probationReminderSent: false },
    },
  })
    .select("name employmentRecords")
    .lean();

  const now = new Date();
  const soon = new Date(now.getTime() + WARN_DAYS_AHEAD * 24 * 60 * 60 * 1000);

  const due: { clientId: string; recordId: string; name: string; probationEnd: Date }[] = [];
  for (const c of candidates) {
    for (const r of c.employmentRecords || []) {
      if (!PROBATION_ELIGIBLE_TYPES.includes(r.type as (typeof PROBATION_ELIGIBLE_TYPES)[number]) || r.probationMonths == null || r.probationReminderSent) continue;
      const probationEnd = probationEndDate(new Date(r.startDate), r.probationMonths);
      if (probationEnd >= now && probationEnd <= soon) {
        due.push({ clientId: String(c._id), recordId: String(r._id), name: c.name, probationEnd });
      }
    }
  }

  if (due.length === 0) return { sent: 0 };

  const rows = due
    .map((d) => `<tr><td style="padding:4px 12px 4px 0;">${d.name}</td><td style="padding:4px 0;">${formatDateDE(d.probationEnd)}</td></tr>`)
    .join("");

  const html = await emailShell({
    heading: "Probezeit endet bald",
    bodyHtml: `
      <p style="margin:0 0 12px;">Bei ${due.length} Mitarbeiter(n) endet die Probezeit in den nächsten ${WARN_DAYS_AHEAD} Tagen:</p>
      <table style="border-collapse:collapse;font-size:14px;"><thead><tr><th style="text-align:left;padding:4px 12px 4px 0;">Name</th><th style="text-align:left;padding:4px 0;">Probezeit endet</th></tr></thead><tbody>${rows}</tbody></table>
    `,
    buttonLabel: "Team verwalten",
    buttonUrl: `${process.env.SITE_URL}/de/admin/team`,
    footerNote: "Automatische Benachrichtigung von rakku.de — einmalig pro Eintrag.",
  });

  try {
    await sendMail(adminEmail, `Probezeit endet bald bei ${due.length} Mitarbeiter(n) — Rakku Photography`, html);
    for (const d of due) {
      await Client.updateOne(
        { _id: d.clientId, "employmentRecords._id": d.recordId },
        { $set: { "employmentRecords.$.probationReminderSent": true } }
      );
    }
    return { sent: due.length };
  } catch (err) {
    console.error("Probezeit-Erinnerung fehlgeschlagen:", err);
    return { sent: 0, error: true };
  }
}
