module.exports = (sequelize, DataTypes) => {
  const BPAddress = sequelize.define('BPAddress', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    bp_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'BusinessPartner',
        key: 'id'
      }
    },
    address_type: {
      type: DataTypes.ENUM('BILLING', 'SHIPPING', 'REGISTERED', 'CORRESPONDENCE', 'OTHER'),
      allowNull: false,
      defaultValue: 'BILLING'
    },
    is_default: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    contact_person: {
      type: DataTypes.STRING(200),
      allowNull: true
    },
    address_line1: {
      type: DataTypes.STRING(200),
      allowNull: true
    },
    address_line2: {
      type: DataTypes.STRING(200),
      allowNull: true
    },
    city_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'City',
        key: 'id'
      }
    },
    state_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'State',
        key: 'id'
      }
    },
    country_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'Country',
        key: 'id'
      }
    },
    pincode: {
      type: DataTypes.STRING(10),
      allowNull: true
    },
    phone: {
      type: DataTypes.STRING(20),
      allowNull: true
    },
    mobile: {
      type: DataTypes.STRING(20),
      allowNull: true
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    effective_from: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    effective_to: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    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: 'bp_address',
    indexes: [
      {
        fields: ['bp_id']
      },
      {
        fields: ['address_type']
      },
      {
        fields: ['status']
      }
    ]
  });

  BPAddress.associate = function(models) {
    BPAddress.belongsTo(models.BusinessPartner, { foreignKey: 'bp_id', as: 'businessPartner' });
    BPAddress.belongsTo(models.City, { foreignKey: 'city_id', as: 'city' });
    BPAddress.belongsTo(models.State, { foreignKey: 'state_id', as: 'state' });
    BPAddress.belongsTo(models.Country, { foreignKey: 'country_id', as: 'country' });
  };

  return BPAddress;
};

