// src/models/csrf-token.ts
// Copyright (C) 2026 Robert Colbert <rob.colbert@openplatform.us>
// All Rights Reserved

import { Schema, model } from "mongoose";

import { GadgetId, IUser } from "@gadget/api";
import { nanoid } from "nanoid";

export interface ICsrfToken {
  _id: GadgetId;
  created: Date;
  expires: Date;
  claimed?: Date;
  token: string;
  user?: IUser | GadgetId;
  ip: string;

  /*
   * not saved
   */
  name?: string;
}

const CsrfTokenSchema = new Schema<ICsrfToken>({
  _id: { type: String, default: () => nanoid() },
  created: {
    type: Date,
    required: true,
    default: Date.now,
    index: -1,
    expires: "72h",
  },
  expires: { type: Date, required: true, default: Date.now, index: -1 },
  claimed: { type: Date },
  token: { type: String, required: true, index: 1 },
  user: { type: String, ref: "User" },
  ip: { type: String, required: true },
});

export const CsrfToken = model<ICsrfToken>("CsrfToken", CsrfTokenSchema);
export default CsrfToken;

(async () => {
  await CsrfToken.syncIndexes();
})();
