import { DataTypes, Model, Optional } from 'sequelize';
import { sequelize } from '../config/database';

export type CodeType = 'HSN' | 'SAC';

export interface HsnSacCodeAttributes {
  id: string;
  code: string;
  type: CodeType;
  gstRate?: number | null;
  description?: string | null;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface HsnSacCodeCreationAttributes extends Optional<HsnSacCodeAttributes, 'id' | 'gstRate' | 'description' | 'isActive' | 'createdAt' | 'updatedAt'> { }

class HsnSacCode extends Model<HsnSacCodeAttributes, HsnSacCodeCreationAttributes> implements HsnSacCodeAttributes {
  public id!: string;
  public code!: string;
  public type!: CodeType;
  public gstRate?: number | null;
  public description?: string | null;
  public isActive!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

HsnSacCode.init({
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true,
  },
  code: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: 'The HSN or SAC code value'
  },
  type: {
    type: DataTypes.ENUM('HSN', 'SAC'),
    allowNull: false,
    comment: 'Type of code: either HSN or SAC'
  },
  gstRate: {
    type: DataTypes.DECIMAL(5, 2),
    allowNull: true,
    field: 'gst_rate',
    comment: 'Associated GST rate percentage'
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: 'Description of the code'
  },
  isActive: {
    type: DataTypes.BOOLEAN,
    defaultValue: true,
    allowNull: false,
    field: 'is_active'
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    field: 'created_at'
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    field: 'updated_at'
  }
}, {
  sequelize,
  modelName: 'HsnSacCode',
  tableName: 'hsn_sac_codes',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      fields: ['code']
    },
    {
      fields: ['type']
    },
    {
      fields: ['is_active']
    }
  ]
});

export { HsnSacCode };
