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

export const QM_STATUSES = ["pending", "approved", "rejected"] as const;
export type QmStatus = (typeof QM_STATUSES)[number];

// Wohin die Einreichung geht — steuert, wer sie sehen und bearbeiten darf
// (Permission "qm" bzw. "hr"). Getrennt, damit vertrauliche Personal-Themen
// nicht automatisch bei allen QM-Prüfern landen.
export const QM_TARGETS = ["qm", "hr"] as const;
export type QmTarget = (typeof QM_TARGETS)[number];

export interface QmSubmissionDoc {
  _id: string;
  target: QmTarget;
  title: string;
  description: string;
  attachmentFilename: string;
  attachmentStoredName: string;
  submittedBy: mongoose.Types.ObjectId;
  // Nur bei target "hr" wählbar — submittedBy bleibt intern gespeichert
  // (fürs Löschen/Verwalten durch die Person selbst), wird aber in der
  // Personalabteilungs-Ansicht nicht angezeigt, wenn anonymous gesetzt ist.
  anonymous: boolean;
  status: QmStatus;
  reviewNote: string;
  reviewedBy: mongoose.Types.ObjectId | null;
  reviewedAt: Date | null;
  createdAt: Date;
}

const qmSubmissionSchema = new Schema<QmSubmissionDoc>(
  {
    target: { type: String, enum: QM_TARGETS, default: "qm" },
    title: { type: String, required: true, trim: true, maxlength: 200 },
    description: { type: String, default: "", trim: true, maxlength: 3000 },
    attachmentFilename: { type: String, default: "" },
    attachmentStoredName: { type: String, default: "" },
    submittedBy: { type: Schema.Types.ObjectId, ref: "Client", required: true },
    anonymous: { type: Boolean, default: false },
    status: { type: String, enum: QM_STATUSES, default: "pending" },
    reviewNote: { type: String, default: "", trim: true, maxlength: 1000 },
    reviewedBy: { type: Schema.Types.ObjectId, ref: "Client", default: null },
    reviewedAt: { type: Date, default: null },
  },
  { timestamps: true }
);

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

export const QmSubmission =
  (models.QmSubmission as mongoose.Model<QmSubmissionDoc>) || model<QmSubmissionDoc>("QmSubmission", qmSubmissionSchema);
