import { connectDB } from "@/lib/db";
import { Todo } from "@/models/Todo";
import { notifyRecipients } from "@/lib/notifications";

// Legt ein automatisch erzeugtes ToDo an — idempotent über `autoKey`, damit
// wiederholte Auslöser (z. B. mehrfaches Speichern eines Termins) nicht
// dutzende gleiche ToDos erzeugen.
export async function ensureAutoTodo(opts: {
  autoKey: string;
  title: string;
  assignedToId: string;
  createdById: string;
  dueDate?: Date | null;
  orderId?: string | null;
  project?: string;
  subtasks?: string[];
  description?: string;
}) {
  if (!opts.assignedToId || !opts.createdById) return;
  await connectDB();
  const existing = await Todo.findOne({ autoKey: opts.autoKey }).select("_id").lean();
  if (existing) return;

  const due = opts.dueDate && !Number.isNaN(opts.dueDate.getTime()) ? opts.dueDate : null;
  const created = await Todo.create({
    title: opts.title.slice(0, 200),
    description: opts.description || "",
    assignedToId: opts.assignedToId,
    createdById: opts.createdById,
    status: "open",
    priority: "normal",
    dueDate: due,
    orderId: opts.orderId || null,
    project: opts.project || "",
    subtasks: (opts.subtasks || []).map((text) => ({ text: text.slice(0, 300), done: false })),
    autoKey: opts.autoKey,
    activity: [{ type: "created", actorId: opts.createdById, text: "Automatisch angelegt" }],
  });

  if (opts.assignedToId !== opts.createdById) {
    await notifyRecipients([opts.assignedToId], {
      type: "todo",
      title: `Neues ToDo: ${opts.title}`,
      body: "Automatisch für dich angelegt.",
      link: `/de/admin/todos#${created._id}`,
    });
  }
}

export async function removeAutoTodo(autoKey: string) {
  await connectDB();
  await Todo.deleteOne({ autoKey, status: { $ne: "done" } });
}

export function daysBefore(date: Date, days: number): Date {
  return new Date(new Date(date).getTime() - days * 24 * 60 * 60 * 1000);
}
