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

// Ledger-Eintrag für jede Änderung an Client.creditBalance (Guthaben-System,
// 28.09.2026) — dient gleichzeitig als Audit-Log (wer/wann/wie viel/warum),
// gleiches Prinzip wie SensitiveDataAccessLog. amount ist positiv bei einer
// Gutschrift, negativ bei einer Abbuchung (z. B. Einlösung bei einem
// Auftrag). balanceAfter ist der Saldo direkt nach dieser Buchung, als
// Schnappschuss gespeichert (nicht neu berechnet), damit die Historie auch
// nachträglich nachvollziehbar bleibt.
export interface CreditTransactionDoc {
  _id: string;
  clientId: mongoose.Types.ObjectId;
  amount: number;
  balanceAfter: number;
  type: "manual_admin" | "cancellation_refund" | "referral_reward" | "order_redemption";
  reason: string;
  // null = systemseitig ausgelöst (z. B. automatische Empfehlungsprämie),
  // sonst die Mitarbeiter:in, die die Buchung manuell vorgenommen hat.
  createdByClientId: mongoose.Types.ObjectId | null;
  relatedOrderId: mongoose.Types.ObjectId | null;
  createdAt: Date;
}

const creditTransactionSchema = new Schema<CreditTransactionDoc>(
  {
    clientId: { type: Schema.Types.ObjectId, ref: "Client", required: true, index: true },
    amount: { type: Number, required: true },
    balanceAfter: { type: Number, required: true },
    type: {
      type: String,
      enum: ["manual_admin", "cancellation_refund", "referral_reward", "order_redemption"],
      required: true,
    },
    reason: { type: String, required: true, trim: true, maxlength: 500 },
    createdByClientId: { type: Schema.Types.ObjectId, ref: "Client", default: null },
    relatedOrderId: { type: Schema.Types.ObjectId, ref: "Order", default: null },
  },
  { timestamps: { createdAt: true, updatedAt: false } }
);

export const CreditTransaction =
  (models.CreditTransaction as mongoose.Model<CreditTransactionDoc>) ||
  model<CreditTransactionDoc>("CreditTransaction", creditTransactionSchema);
