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

import { Schema, model } from "mongoose";
import { ChatSessionMode, IChatSession, IChatSessionPin } from "@gadget/api";
import { nanoid } from "nanoid";

export const ChatSessionPinSchema = new Schema<IChatSessionPin>({
  content: { type: String, required: true },
});

export const ChatSessionSchema = new Schema<IChatSession>({
  _id: { type: String, default: () => nanoid() },
  createdAt: { type: Date, default: Date.now, required: true },
  lastMessageAt: { type: Date },
  user: { type: String, required: true, index: 1, ref: "User" },
  project: { type: String, required: false, index: 1, ref: "Project" },
  name: { type: String, default: "New Session", required: true },
  mode: {
    type: String,
    enum: ChatSessionMode,
    default: ChatSessionMode.Build,
    required: true,
  },
  provider: { type: String, required: true, ref: "AiProvider" },
  selectedModel: { type: String, required: true },
  reasoningEffort: {
    type: String,
    enum: ["off", "low", "medium", "high"],
    default: "off",
  },
  numCtx: { type: Number },
  stats: {
    turnCount: { type: Number, default: 0, required: true },
    toolCallCount: { type: Number, default: 0, required: true },
    inputTokens: { type: Number, default: 0, required: true },
    outputTokens: { type: Number, default: 0, required: true },
  },
  pins: { type: [ChatSessionPinSchema], default: [], required: true },
});

export const ChatSession = model<IChatSession>(
  "ChatSession",
  ChatSessionSchema,
);

export default ChatSession;
