/**
 * ChatSession Model - Multi-session chat history persistence
 *
 * Each document represents one conversation session.
 * A user can have multiple sessions per company.
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// INTERFACES
// ============================================

export interface IChatMessage {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: Date;
  moduleId?: string;
  context?: Record<string, unknown>;
}

export interface IChatSession extends Document {
  companyId: string;
  userId: string;
  title: string;
  messages: IChatMessage[];
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SCHEMA
// ============================================

const ChatMessageSchema = new Schema<IChatMessage>({
  id: { type: String, required: true },
  role: {
    type: String,
    enum: ['user', 'assistant', 'system'],
    required: true,
  },
  content: { type: String, required: true },
  timestamp: { type: Date, default: Date.now },
  moduleId: { type: String },
  context: { type: Schema.Types.Mixed },
}, { _id: false });

const ChatSessionSchema = new Schema<IChatSession>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true,
  },
  userId: {
    type: String,
    required: [true, 'User ID is required'],
    index: true,
  },
  title: {
    type: String,
    default: 'New Chat',
    trim: true,
    maxlength: [200, 'Title cannot exceed 200 characters'],
  },
  messages: [ChatMessageSchema],
}, {
  timestamps: true,
});

// ============================================
// INDEXES
// ============================================

// For listing sessions sorted by recent activity
ChatSessionSchema.index({ companyId: 1, userId: 1, updatedAt: -1 });
// For finding a specific user's sessions
ChatSessionSchema.index({ companyId: 1, userId: 1 });

// ============================================
// MODEL
// ============================================

const ChatSession = mongoose.models.ChatSession as mongoose.Model<IChatSession>
  || mongoose.model<IChatSession>('ChatSession', ChatSessionSchema);

export { ChatSession, ChatSessionSchema };