import mongoose, { Schema, models, model } from "mongoose";
import { TODO_PRIORITIES, type TodoPriority } from "@/models/Todo";

// Vorlage für einen Satz ToDos, den man oft am Stück braucht (z. B. die
// Standard-Vorbereitung für eine Convention). Beim Anwenden entsteht pro
// Eintrag ein echtes ToDo; `dueOffsetDays` wird auf das gewählte Startdatum
// aufgeschlagen.
export interface TodoTemplateItemDoc {
  _id: string;
  title: string;
  description: string;
  priority: TodoPriority;
  dueOffsetDays: number | null;
  labels: string[];
  subtasks: string[];
}

export interface TodoTemplateDoc {
  _id: string;
  name: string;
  defaultProject: string;
  items: TodoTemplateItemDoc[];
  createdById: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

const itemSchema = new Schema<TodoTemplateItemDoc>(
  {
    title: { type: String, required: true, trim: true, maxlength: 200 },
    description: { type: String, default: "", trim: true, maxlength: 2000 },
    priority: { type: String, enum: TODO_PRIORITIES, default: "normal" },
    dueOffsetDays: { type: Number, default: null },
    labels: { type: [String], default: [] },
    subtasks: { type: [String], default: [] },
  },
  { _id: true }
);

const todoTemplateSchema = new Schema<TodoTemplateDoc>(
  {
    name: { type: String, required: true, trim: true, maxlength: 120 },
    defaultProject: { type: String, default: "", trim: true, maxlength: 80 },
    items: { type: [itemSchema], default: [] },
    createdById: { type: Schema.Types.ObjectId, ref: "Client", required: true },
  },
  { timestamps: true }
);

export const TodoTemplate =
  (models.TodoTemplate as mongoose.Model<TodoTemplateDoc>) ||
  model<TodoTemplateDoc>("TodoTemplate", todoTemplateSchema);
