const { DataTypes } = require("sequelize");

module.exports = (sequelize) => {
  const Vehicle = sequelize.define(
    "vehicle",
    {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true,
      },
      creation: { type: DataTypes.DATE, allowNull: false },
      modified: { type: DataTypes.DATE, allowNull: false },
      modified_by: { type: DataTypes.INTEGER, allowNull: false },
      owner: { type: DataTypes.INTEGER, allowNull: false },
      enabled: { type: DataTypes.BOOLEAN, allowNull: false },

      license_plate: { type: DataTypes.STRING(100), allowNull: false, unique: true },
      plate_date: { type: DataTypes.STRING(100), allowNull: true },
      model: { type: DataTypes.STRING(100), allowNull: true },
      fuel_type: { type: DataTypes.STRING(100), allowNull: true },
      fuel_uom: { type: DataTypes.STRING(100), allowNull: true },
      odometer_value: { type: DataTypes.INTEGER, allowNull: true },

      // fk
      company_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: {
          model: 'companies',
          key: 'id'
        }
      }
    },
    {
      tableName: "vehicles",
      freezeTableName: true,
    }
  );

  /**
   * Associates the Vehicle model with other models.
   * @param {object} models - The models to associate with.
   */
  Vehicle.associate = (models) => {

    /**
     * A Vehicle belongs to a Company.
     * Defines a many-to-one relationship between Vehicle and Company.
     * @param {object} models - The models to associate with.
     */
    Vehicle.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });
    
    /**
     * Associates the Vehicle model with the DeliveryTrip model.
     * Defines a one-to-many relationship between Company and DeliveryTrip.
     * @param {object} models - The models to associate with.
     */
    Vehicle.hasMany(models.DeliveryTrip, { foreignKey: "vehicle_id", as: "vehicles" });

  };

  return Vehicle;
};
