module.exports = (sequelize, DataTypes) => {
  const CurrencyRate = sequelize.define('CurrencyRate', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    currency_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Currency',
        key: 'id'
      }
    },
    base_currency_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Currency',
        key: 'id'
      }
    },
    exchange_rate: {
      type: DataTypes.DECIMAL(15, 6),
      allowNull: false
    },
    rate_type: {
      type: DataTypes.ENUM('BUY', 'SELL', 'MID'),
      allowNull: false,
      defaultValue: 'MID'
    },
    valid_from: {
      type: DataTypes.DATEONLY,
      allowNull: false
    },
    valid_to: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    created_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    },
    updated_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    }
  }, {
    tableName: 'currency_rate',
    indexes: [
      {
        fields: ['currency_id']
      },
      {
        fields: ['base_currency_id']
      },
      {
        fields: ['valid_from', 'valid_to']
      },
      {
        fields: ['status']
      },
      {
        unique: true,
        fields: ['currency_id', 'base_currency_id', 'rate_type', 'valid_from']
      }
    ]
  });

  CurrencyRate.associate = function(models) {
    CurrencyRate.belongsTo(models.Currency, { foreignKey: 'currency_id', as: 'currency' });
    CurrencyRate.belongsTo(models.Currency, { foreignKey: 'base_currency_id', as: 'baseCurrency' });
  };

  return CurrencyRate;
};

