import { DataTypes, Model, Optional } from "sequelize";
import sequelize from "@/lib/sequelize";

// 1. Define attributes
interface UserAttributes {
  id: number;
  email: string;
  name: string | null;
  password?: string;
  role: string;
  isActive: boolean;
  lastLogin?: Date | null;
  loginAttempts: number;
  lockedUntil?: Date | null;
  createdAt?: Date;
  updatedAt?: Date;
}

// 2. Define creation attributes
type UserCreationAttributes = Optional<
  UserAttributes,
  "id" | "name" | "role" | "isActive" | "lastLogin" | "loginAttempts" | "lockedUntil" | "createdAt" | "updatedAt"
>;

// 3. Define the Model class
class User extends Model<UserAttributes, UserCreationAttributes> implements UserAttributes {
  public id!: number;
  public email!: string;
  public name!: string | null;
  public password!: string;
  public role!: string;
  public isActive!: boolean;
  public lastLogin!: Date | null;
  public loginAttempts!: number;
  public lockedUntil!: Date | null;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

// 4. Initialize the model
User.init(
  {
    id: {
      type: DataTypes.INTEGER.UNSIGNED,
      autoIncrement: true,
      primaryKey: true,
    },
    email: {
      type: DataTypes.STRING(191),
      allowNull: false,
      unique: true,
    },
    name: {
      type: DataTypes.STRING(191),
      allowNull: true,
    },
    password: {
      type: DataTypes.STRING(191),
      allowNull: false,
    },
    role: {
      type: DataTypes.STRING(50),
      allowNull: false,
      defaultValue: "USER",
    },
    isActive: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: true,
    },
    lastLogin: {
      type: DataTypes.DATE(3),
      allowNull: true,
    },
    loginAttempts: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
    },
    lockedUntil: {
      type: DataTypes.DATE(3),
      allowNull: true,
    },
    createdAt: {
      type: DataTypes.DATE(3),
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updatedAt: {
      type: DataTypes.DATE(3),
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  },
  {
    sequelize,
    tableName: "users",
    timestamps: true,
    updatedAt: "updatedAt",
    createdAt: "createdAt",
  }
);

export default User;
