const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const MonthlyDraw = sequelize.define('MonthlyDraw', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true
  },
  group_id: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
      model: 'chit_groups',
      key: 'id'
    }
  },
  month: {
    type: DataTypes.INTEGER,
    allowNull: false,
    validate: {
      min: 1,
      max: 12
    }
  },
  year: {
    type: DataTypes.INTEGER,
    allowNull: false,
    validate: {
      min: 2020
    }
  },
  draw_date: {
    type: DataTypes.DATE,
    allowNull: false
  },
  eligible_members: {
    type: DataTypes.JSONB,
    allowNull: false,
    defaultValue: []
  },
  winner_id: {
    type: DataTypes.UUID,
    allowNull: true,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  prize_amount: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: true,
    validate: {
      min: 0
    }
  },
  server_seed: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  server_seed_hash: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  client_seed: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  nonce: {
    type: DataTypes.BIGINT,
    allowNull: false
  },
  result_hash: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  status: {
    type: DataTypes.ENUM('pending', 'completed', 'cancelled'),
    defaultValue: 'pending'
  },
  notes: {
    type: DataTypes.TEXT,
    allowNull: true
  }
}, {
  tableName: 'monthly_draws',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      unique: true,
      fields: ['group_id', 'month', 'year']
    }
  ]
});

module.exports = MonthlyDraw;
