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

const TranslationMapping = sequelize.define('TranslationMapping', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true
  },
  dictionaryId: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
      model: 'TranslationDictionaries',
      key: 'id'
    },
    onDelete: 'CASCADE'
  },
  sourceToken: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: true
    }
  },
  targetToken: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: true
    }
  },
  transformRule: {
    type: DataTypes.JSONB,
    defaultValue: null,
    comment: 'Optional transformation rules (scale, convert units, etc.)'
  },
  validated: {
    type: DataTypes.BOOLEAN,
    defaultValue: false
  },
  confidence: {
    type: DataTypes.FLOAT,
    defaultValue: 1.0,
    validate: {
      min: 0,
      max: 1
    },
    comment: 'Confidence score for auto-generated mappings (0-1)'
  },
  notes: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  createdAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updatedAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  timestamps: true,
  indexes: [
    { fields: ['dictionaryId'] },
    { fields: ['sourceToken'] },
    { fields: ['targetToken'] },
    { fields: ['validated'] },
    // Composite unique constraint: one source token can only map to one target per dictionary
    {
      unique: true,
      fields: ['dictionaryId', 'sourceToken']
    }
  ]
});

export default TranslationMapping;
