module.exports = function (sequelize, DataTypes) {
  const Invoice = sequelize.define('invoices', {
    id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    unit_id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
    },
    invoice_no: {
      type: DataTypes.STRING(100),
      allowNull: false,
    },
    issue_date: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    due_date: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    note: {
      type: DataTypes.TEXT('long'),
      allowNull: true,
    },
    subtotal: {
      type: DataTypes.DOUBLE(15, 2),
      defaultValue: 0.00,
    },
    discount_type: {
      type: DataTypes.STRING(10),
      allowNull: true,
    },
    discount: {
      type: DataTypes.DOUBLE(15, 2),
      defaultValue: 0.00,
    },
    total: {
      type: DataTypes.DOUBLE(15, 2),
      defaultValue: 0.00,
    },
    balance: {
      type: DataTypes.DOUBLE(15, 2),
      defaultValue: 0.00,
    },
    paid_amount: {
      type: DataTypes.DOUBLE(15, 2),
      defaultValue: 0.00,
    },
    status: {
      type: DataTypes.ENUM('paid', 'unpaid', 'partial'),
      allowNull: false,
      defaultValue: 'unpaid',
    },
    send_email: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
    },
    print_invoice: {
      type: DataTypes.ENUM('true', 'false'),
      defaultValue: 'false',
    },
    print_fax: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
    },
    type: {
      type: DataTypes.ENUM('client', 'tenant'),
      allowNull: false,
      defaultValue: 'tenant',
    },
    created_by: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
    },
    createdAt: {
      field: 'created_at',
      type: DataTypes.DATE,
    },
    updatedAt: {
      field: 'updated_at',
      type: DataTypes.DATE,
    },
  }, {
    timestamps: true,
    underscored: true,
    freezeTableName: true,
    tableName: 'invoices',
    indexes: [
      {
        unique: true,
        name: 'unique_invoice_per_unit',
        fields: ['unit_id', 'invoice_no'],
      },
    ],
  });

  Invoice.associate = function (models) {
    Invoice.hasMany(models.invoice_items, {
      foreignKey: 'invoice_id',
      as: 'items',
      onDelete: 'CASCADE',
      hooks: true,
      constraints: true   // ← ADD THIS
    });  

    Invoice.hasMany(models.tenant_invoices, {
      foreignKey: 'invoice_id',
      as: 'tenant_invoices',
      onDelete: 'CASCADE',
      constraints: true   // ← ADD THIS
    });

    Invoice.hasMany(models.client_invoices, {
      foreignKey: 'invoice_id',
      as: 'client_invoices',
      onDelete: 'CASCADE',
      constraints: true   // ← ADD THIS
    });
  };

  return Invoice;
}; 