import mongoose, { Schema, models, model } from "mongoose";

// Deckt sowohl Mitarbeiter- als auch Kundenbenachrichtigungen ab (role des
// jeweiligen Client-Dokuments entscheidet, wo die Glocke erscheint) — ein
// Modell statt zwei, da Struktur/Handling identisch sind.
export const NOTIFICATION_TYPES = [
  "new_order",
  "new_message_for_staff",
  "new_message_for_client",
  "qm_submission",
  "payment_reminder",
  "contract_reminder",
  "waitlist_slot_open",
  "weather_warning",
  "review_reward",
  "loyalty_reward",
  "todo",
] as const;
export type NotificationType = (typeof NOTIFICATION_TYPES)[number];

export interface NotificationDoc {
  _id: string;
  recipientId: mongoose.Types.ObjectId;
  type: NotificationType;
  title: string;
  body: string;
  link: string;
  read: boolean;
  createdAt: Date;
}

const notificationSchema = new Schema<NotificationDoc>(
  {
    recipientId: { type: Schema.Types.ObjectId, ref: "Client", required: true, index: true },
    type: { type: String, enum: NOTIFICATION_TYPES, required: true },
    title: { type: String, required: true, trim: true, maxlength: 200 },
    body: { type: String, default: "", trim: true, maxlength: 500 },
    link: { type: String, default: "", trim: true },
    read: { type: Boolean, default: false, index: true },
  },
  { timestamps: { createdAt: true, updatedAt: false } }
);

// Das Systemprotokoll (lib/logFeed.ts) filtert/sortiert nach createdAt.
notificationSchema.index({ createdAt: -1 });

export const Notification =
  (models.Notification as mongoose.Model<NotificationDoc>) || model<NotificationDoc>("Notification", notificationSchema);
