module.exports = (sequelize, DataTypes) => {
  const AccountingDocumentItem = sequelize.define('AccountingDocumentItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    document_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'AccountingDocument',
        key: 'id',
        onDelete: 'CASCADE'
      }
    },
    line_number: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: 'Line item sequence number'
    },
    gl_account_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'GLAccount',
        key: 'id'
      }
    },
    cost_center_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'CostCenter',
        key: 'id'
      }
    },
    debit_amount: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0,
      comment: 'Debit amount in base currency'
    },
    credit_amount: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0,
      comment: 'Credit amount in base currency'
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: 'Line item description'
    },
    reference_type: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: 'Additional reference type if needed'
    },
    reference_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: 'Additional reference ID if needed'
    },
    reference_text: {
      type: DataTypes.STRING(200),
      allowNull: true,
      comment: 'Additional reference text'
    }
  }, {
    tableName: 'accounting_document_item',
    indexes: [
      {
        fields: ['document_id']
      },
      {
        fields: ['gl_account_id']
      },
      {
        fields: ['cost_center_id']
      }
    ]
  });

  AccountingDocumentItem.associate = function(models) {
    AccountingDocumentItem.belongsTo(models.AccountingDocument, { foreignKey: 'document_id', as: 'document' });
    AccountingDocumentItem.belongsTo(models.GLAccount, { foreignKey: 'gl_account_id', as: 'glAccount' });
    AccountingDocumentItem.belongsTo(models.CostCenter, { foreignKey: 'cost_center_id', as: 'costCenter' });
  };

  return AccountingDocumentItem;
};

