import { DataTypes } from 'sequelize';
import sequelize from '../config/database.js';

const AIChat = sequelize.define('AIChat', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true
  },
  projectId: {
    type: DataTypes.UUID,
    allowNull: true,
    references: {
      model: 'projects',
      key: 'id'
    }
  },
  userId: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  sessionId: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    index: true
  },
  messageType: {
    type: DataTypes.ENUM('claude-query', 'ai-query', 'navigation-gen', 'token-save'),
    allowNull: false
  },
  status: {
    type: DataTypes.ENUM('pending', 'processing', 'completed', 'failed'),
    defaultValue: 'pending',
    index: true
  },
  userMessage: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  aiResponse: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  generatedCode: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  navigationStructure: {
    type: DataTypes.JSON,
    allowNull: true
  },
  tokens: {
    type: DataTypes.JSON,
    allowNull: true
  },
  inputTokens: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  outputTokens: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  model: {
    type: DataTypes.STRING,
    defaultValue: 'mock-ai-v1'
  },
  error: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  metadata: {
    type: DataTypes.JSON,
    defaultValue: {}
  },
  startedAt: {
    type: DataTypes.DATE,
    allowNull: true
  },
  completedAt: {
    type: DataTypes.DATE,
    allowNull: true
  }
}, {
  tableName: 'ai_chats',
  timestamps: true,
  indexes: [
    { fields: ['userId', 'createdAt'] },
    { fields: ['projectId', 'status'] },
    { fields: ['sessionId'] },
    { fields: ['status'] }
  ]
});

export default AIChat;
