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

// Extrahiert aus admin/todos/page.tsx — Feldumfang deckt inzwischen alles ab,
// was die Seite selbst brauchte (vorher lief die Seite noch mit einer eigenen,
// abweichenden Inline-Query mit mehr Feldern als hier — jetzt eine Quelle).
export async function getTodoList(viewerId: string, canViewAll: boolean) {
  await connectDB();
  const rawTodos = canViewAll
    ? await Todo.find({}).sort({ createdAt: -1 }).lean()
    : await Todo.find({
        $or: [
          { assignedToId: viewerId },
          { createdById: viewerId },
          { additionalAssigneeIds: viewerId },
          { watcherIds: viewerId },
        ],
      })
        .sort({ createdAt: -1 })
        .lean();

  return rawTodos.map((t) => ({
    _id: String(t._id),
    title: t.title,
    description: t.description,
    assignedToId: String(t.assignedToId),
    additionalAssigneeIds: (t.additionalAssigneeIds || []).map(String),
    watcherIds: (t.watcherIds || []).map(String),
    createdById: String(t.createdById),
    status: t.status,
    priority: t.priority,
    dueDate: t.dueDate ? new Date(t.dueDate).toISOString() : null,
    orderId: t.orderId ? String(t.orderId) : null,
    labels: t.labels || [],
    project: t.project || "",
    subtasks: (t.subtasks || []).map((s) => ({ id: String(s._id), text: s.text, done: Boolean(s.done) })),
    attachments: (t.attachments || []).map((a) => ({
      filename: a.filename,
      storedName: a.storedName,
      size: a.size,
      mimeType: a.mimeType,
    })),
    activity: (t.activity || [])
      .slice(-20)
      .map((a) => ({
        type: a.type,
        actorId: String(a.actorId),
        text: a.text,
        createdAt: new Date(a.createdAt).toISOString(),
      })),
    notes: t.notes.map((n) => ({
      _id: String(n._id),
      authorId: String(n.authorId),
      text: n.text,
      createdAt: new Date(n.createdAt).toISOString(),
    })),
    createdAt: new Date(t.createdAt).toISOString(),
    recurrence: t.recurrence,
    recurrenceInterval: t.recurrenceInterval || 1,
    recurrenceWeekdays: t.recurrenceWeekdays || [],
    recurrenceEndDate: t.recurrenceEndDate ? new Date(t.recurrenceEndDate).toISOString() : null,
  }));
}

// Extrahiert aus admin/todos/page.tsx — dieselbe "Zeile" | "+N" | "#Label" |
// "hoch"-Textdarstellung, die parseTemplateLine() (actions/todos.ts) beim
// Speichern wieder zurückparst, damit die Vorlage in einem einzigen Textfeld
// bearbeitbar bleibt (Web-Textarea, App-Textfeld — dieselbe Kodierung).
export async function getTodoTemplateList() {
  await connectDB();
  const templateDocs = await TodoTemplate.find({}).sort({ name: 1 }).lean();
  return templateDocs.map((tpl) => ({
    id: String(tpl._id),
    name: tpl.name,
    defaultProject: tpl.defaultProject || "",
    itemCount: tpl.items.length,
    itemsText: tpl.items
      .map((it) => {
        const parts: string[] = [it.title];
        if (it.dueOffsetDays != null) parts.push(`+${it.dueOffsetDays}`);
        if (it.labels.length) parts.push(it.labels.map((l) => `#${l}`).join(" "));
        if (it.priority !== "normal") parts.push(it.priority === "high" ? "hoch" : "niedrig");
        return parts.join(" | ");
      })
      .join("\n"),
  }));
}
