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

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

import { ChatSessionMode } from "./chat-session.js";

/*
 * A skill is a recipe an agent can follow, or knowledge an agent will need,
 * while working on tasks for Users. Skills are stored in the database and can
 * be created, updated, and deleted by Users and by Agents using the skills
 * tool(s).
 *
 * The User will have a Skills editor, which lets them maintain their library
 * of skills that is unique to that User. Skills that don't have a User are
 * global and accessible to all Agents in all sessions.
 */

export interface IAiSkillHistory {
  version: number;
  name: string;
  description: string;
  tags: string[];
  modes: ChatSessionMode[];
  content: string;
}
export const AiSkillHistorySchema = new Schema<IAiSkillHistory>({
  version: { type: Number, required: true },
  name: { type: String, required: true },
  description: { type: String, required: true },
  tags: { type: [String], default: [] },
  modes: { type: [String], enum: ChatSessionMode, default: [] },
  content: { type: String, required: true },
});

export interface IAiSkill extends Document {
  _id: Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
  user: Types.ObjectId | null; // null means "global" skill (available to all users)
  name: string;
  description: string;
  tags: string[];
  modes: ChatSessionMode[];
  content: string;
  history: IAiSkillHistory[];
}

export const AiSkillSchema = new Schema<IAiSkill>({
  createdAt: { type: Date, default: Date.now, required: true },
  updatedAt: { type: Date, default: Date.now, required: true },
  user: { type: Types.ObjectId, null: true, index: 1, ref: "User" },
  name: { type: String, required: true },
  description: { type: String, required: true },
  tags: { type: [String], default: [] },
  modes: { type: [String], enum: ChatSessionMode, default: [] },
  content: { type: String, required: true },
  history: { type: [AiSkillHistorySchema], default: [], required: true },
});

AiSkillSchema.index(
  { name: "text", description: "text", tags: "text" },
  {
    weights: {
      name: 5,
      description: 3,
      tags: 1,
    },
    name: "AiSkillTextIndex",
  },
);

export const AiSkill = model<IAiSkill>("AiSkill", AiSkillSchema);
export default AiSkill;

// Note: Index synchronization is now handled during application startup
// to ensure the database connection is established first.
// See src/lib/db.ts for the syncDatabaseIndexes function.
