import mongoose, { Schema, models, model } from "mongoose";
import { DOCUMENT_CATEGORIES, type DocumentCategory } from "@/lib/documentConstants";

export interface GeneratedDocumentDoc {
  _id: string;
  templateId: mongoose.Types.ObjectId | null;
  templateName: string;
  category: DocumentCategory;
  clientId: mongoose.Types.ObjectId | null;
  clientName: string;
  // Voller Dokumenttext, frei bearbeitbar beim Erstellen und danach —
  // unabhängig von der Vorlage gespeichert, spätere Vorlagenänderungen
  // wirken sich nicht rückwirkend auf bereits erstellte Dokumente aus.
  renderedBody: string;
  includeLetterhead: boolean;
  includeFooter: boolean;
  footerText: string;
  includeRecipientAddress: boolean;
  recipientAddress: string;
  createdBy: mongoose.Types.ObjectId;
  // Einfache elektronische Unterschrift (Name + Zeitstempel + IP), analog
  // zur bestehenden TFP-Vertragsunterschrift — kein gezeichnetes Bild, kein
  // qualifiziertes Signaturverfahren, aber ausreichend als Nachweis für
  // interne Personaldokumente.
  signature: { name: string; signedAt: Date; ip: string } | null;
  createdAt: Date;
  updatedAt: Date;
}

const generatedDocumentSchema = new Schema<GeneratedDocumentDoc>(
  {
    templateId: { type: Schema.Types.ObjectId, ref: "DocumentTemplate", default: null },
    templateName: { type: String, default: "" },
    category: { type: String, enum: DOCUMENT_CATEGORIES, default: "other" },
    clientId: { type: Schema.Types.ObjectId, ref: "Client", default: null },
    clientName: { type: String, default: "" },
    renderedBody: { type: String, required: true },
    includeLetterhead: { type: Boolean, default: true },
    includeFooter: { type: Boolean, default: true },
    footerText: { type: String, default: "" },
    includeRecipientAddress: { type: Boolean, default: false },
    recipientAddress: { type: String, default: "" },
    createdBy: { type: Schema.Types.ObjectId, ref: "Client", required: true },
    signature: {
      type: new Schema({ name: String, signedAt: Date, ip: String }, { _id: false }),
      default: null,
    },
  },
  { timestamps: true }
);

export const GeneratedDocument =
  (models.GeneratedDocument as mongoose.Model<GeneratedDocumentDoc>) ||
  model<GeneratedDocumentDoc>("GeneratedDocument", generatedDocumentSchema);
