'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('accounting_document_item', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      document_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'accounting_document',
          key: 'id',
          onDelete: 'CASCADE'
        }
      },
      line_number: {
        type: Sequelize.INTEGER,
        allowNull: false
      },
      gl_account_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'gl_account',
          key: 'id'
        }
      },
      cost_center_id: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'cost_center',
          key: 'id'
        }
      },
      debit_amount: {
        type: Sequelize.DECIMAL(18, 2),
        allowNull: false,
        defaultValue: 0
      },
      credit_amount: {
        type: Sequelize.DECIMAL(18, 2),
        allowNull: false,
        defaultValue: 0
      },
      description: {
        type: Sequelize.STRING(500),
        allowNull: true
      },
      reference_type: {
        type: Sequelize.STRING(50),
        allowNull: true
      },
      reference_id: {
        type: Sequelize.INTEGER,
        allowNull: true
      },
      reference_text: {
        type: Sequelize.STRING(200),
        allowNull: true
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
      }
    });

    await queryInterface.addIndex('accounting_document_item', ['document_id'], {
      name: 'idx_accounting_document_item_document'
    });

    await queryInterface.addIndex('accounting_document_item', ['gl_account_id'], {
      name: 'idx_accounting_document_item_gl_account'
    });

    await queryInterface.addIndex('accounting_document_item', ['cost_center_id'], {
      name: 'idx_accounting_document_item_cost_center'
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('accounting_document_item');
  }
};

