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

const AlphaInvitation = sequelize.define(
  "AlphaInvitation",
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    code: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: false,
      validate: {
        is: /^ALPHA-[A-Z0-9]{8}$/i,
      },
    },
    email: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: false,
      validate: {
        isEmail: true,
      },
      set(value) {
        // Normalize email to lowercase
        this.setDataValue("email", value.toLowerCase().trim());
      },
    },
    usedBy: {
      type: DataTypes.UUID,
      allowNull: true,
      references: {
        model: "Users",
        key: "id",
      },
    },
    usedAt: {
      type: DataTypes.DATE,
      allowNull: true,
    },
    status: {
      type: DataTypes.ENUM("pending", "active", "revoked"),
      defaultValue: "pending",
      allowNull: false,
    },
  },
  {
    indexes: [
      {
        fields: ["code"],
      },
      {
        fields: ["email"],
      },
      {
        fields: ["status"],
      },
    ],
  }
);

module.exports = AlphaInvitation;
