'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('currency_rate', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      currency_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'currency',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      base_currency_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'currency',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      exchange_rate: {
        type: Sequelize.DECIMAL(15, 6),
        allowNull: false
      },
      rate_type: {
        type: Sequelize.ENUM('BUY', 'SELL', 'MID'),
        allowNull: false,
        defaultValue: 'MID'
      },
      valid_from: {
        type: Sequelize.DATEONLY,
        allowNull: false
      },
      valid_to: {
        type: Sequelize.DATEONLY,
        allowNull: true
      },
      status: {
        type: Sequelize.ENUM('ACTIVE', 'INACTIVE'),
        allowNull: false,
        defaultValue: 'ACTIVE'
      },
      created_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      },
      updated_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      },
      created_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updated_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
      }
    });

    await queryInterface.addIndex('currency_rate', ['currency_id']);
    await queryInterface.addIndex('currency_rate', ['base_currency_id']);
    await queryInterface.addIndex('currency_rate', ['valid_from', 'valid_to']);
    await queryInterface.addIndex('currency_rate', ['status']);
    await queryInterface.addIndex('currency_rate', ['currency_id', 'base_currency_id', 'rate_type', 'valid_from'], { unique: true, name: 'currency_rate_uniq_key' });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('currency_rate');
  }
};

