module.exports = (sequelize, DataTypes) => {
  const TaxMaster = sequelize.define('TaxMaster', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    tax_code: {
      type: DataTypes.STRING(20),
      allowNull: false
    },
    tax_name: {
      type: DataTypes.STRING(200),
      allowNull: false
    },
    tax_type: {
      type: DataTypes.ENUM('GST', 'TDS', 'TCS', 'EXCISE', 'CUSTOMS', 'VAT', 'CESS', 'OTHER'),
      allowNull: false
    },
    tax_rate: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: false,
      defaultValue: 0.00,
      comment: 'Tax rate in percentage'
    },
    cgst_rate: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: true,
      comment: 'CGST rate for GST type'
    },
    sgst_rate: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: true,
      comment: 'SGST rate for GST type'
    },
    igst_rate: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: true,
      comment: 'IGST rate for GST type'
    },
    cess_rate: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: true,
      comment: 'CESS rate for GST type'
    },
    gl_account_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'GLAccount',
        key: 'id'
      },
      comment: 'GL account for tax liability'
    },
    input_gl_account_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'GLAccount',
        key: 'id'
      },
      comment: 'GL account for input tax credit'
    },
    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: 'tax_master',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'tax_code']
      },
      {
        fields: ['tax_type']
      },
      {
        fields: ['status']
      },
      {
        fields: ['effective_from', 'effective_to']
      }
    ]
  });

  TaxMaster.associate = function(models) {
    TaxMaster.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    TaxMaster.belongsTo(models.GLAccount, { foreignKey: 'gl_account_id', as: 'glAccount' });
    TaxMaster.belongsTo(models.GLAccount, { foreignKey: 'input_gl_account_id', as: 'inputGLAccount' });
  };

  return TaxMaster;
};

