// src/models/chat-session.ts
// Copyright (C) 2025 DTP Technologies, LLC
// All Rights Reserved

import { Types, Schema, Document, model } from "mongoose";

import { IUser } from "./user.js";
import { IProject } from "./project.js";

export enum ChatSessionType {
  Desktop = "desktop",
  Mobile = "mobile",
  Extension = "extension",
}

export enum ChatSessionMode {
  Plan = "plan", // for planning and brainstorming
  Build = "build", // for building and coding
  Test = "test", // for testing and debugging
  Ship = "ship", // for finalizing and shipping
  Develop = "dev", // for working on the Gadget Code agentic harness itself
}

export interface IChatSessionPin {
  _id?: Types.ObjectId;
  content: string;
}

export interface IChatSession extends Document {
  createdAt: Date;
  lastMessageAt?: Date;
  user: IUser | Types.ObjectId;
  project: IProject | Types.ObjectId;
  name: string;
  type: ChatSessionType;
  mode: ChatSessionMode;
  stats: {
    turnCount: number;
    toolCallCount: number;
    inputTokens: number;
    outputTokens: number;
  };
  pins: IChatSessionPin[];
}
export const ChatSessionPinSchema = new Schema<IChatSessionPin>({
  content: { type: String, required: true },
});

export const ChatSessionSchema = new Schema<IChatSession>({
  createdAt: { type: Date, default: Date.now, required: true },
  lastMessageAt: { type: Date },
  user: { type: Types.ObjectId, required: true, index: 1, ref: "User" },
  project: { type: Types.ObjectId, required: false, index: 1, ref: "Project" },
  name: { type: String, default: "New Session", required: true },
  type: {
    type: String,
    enum: ChatSessionType,
    default: ChatSessionType.Desktop,
    required: true,
  },
  mode: {
    type: String,
    enum: ChatSessionMode,
    default: ChatSessionMode.Build,
    required: true,
  },
  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;
