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

import { Schema, model } from "mongoose";

import {
  ProjectStatus,
  IProject,
  IProjectSkill,
  ChatSessionMode,
  IProjectTask,
} from "@gadget/api";
import { nanoid } from "nanoid";

export const ProjectSkillSchema = new Schema<IProjectSkill>({
  _id: { type: String, default: () => nanoid() },
  name: { type: String, required: true },
  modes: { type: [String], enum: ChatSessionMode, required: true },
  content: { type: String, required: true },
});

export const ProjectTaskSchema = new Schema<IProjectTask>({
  _id: { type: String, default: () => nanoid() },
  name: { type: String, required: true },
  provider: { type: String, required: true, ref: "AiProvider" },
  selectedModel: { type: String, required: true },
  mode: { type: String, enum: ChatSessionMode, required: true },
  crontab: { type: String, required: true },
  content: { type: String, required: true },
  enabled: { type: Boolean, default: true, required: true },
  lastRun: { type: String, ref: "ChatSession" },
});

export const ProjectSchema = new Schema<IProject>({
  _id: { type: String, default: () => nanoid() },
  createdAt: { type: Date, default: Date.now, required: true },
  user: { type: String, required: true, index: 1, ref: "User" },
  status: { type: String, enum: ProjectStatus, required: true },
  name: { type: String, default: "New Project", required: true },
  slug: {
    type: String,
    default: "new-project",
    lowercase: true,
    required: true,
  },
  gitUrl: { type: String },
  description: { type: String },
  system: { type: String },
  skills: { type: [ProjectSkillSchema], default: [], required: true },
  tasks: { type: [ProjectTaskSchema], default: [], required: true },
});

ProjectSchema.index(
  {
    user: 1,
    slug: 1,
  },
  {
    unique: true,
  },
);

ProjectSchema.index(
  {
    user: 1,
    gitUrl: 1,
  },
  {
    partialFilterExpression: {
      gitUrl: { $exists: true },
    },
    unique: true,
  },
);

export const Project = model<IProject>("Project", ProjectSchema);

export default Project;
