import { USER_ROLES } from "@/contexts/users";
import { DataTypes, InferAttributes, InferCreationAttributes, Model, Sequelize } from "sequelize";

export type AuthUserCreationAttributes = InferCreationAttributes<AuthUser_Model>;

export class AuthUser_Model extends Model<
  InferAttributes<AuthUser_Model>,
  InferCreationAttributes<AuthUser_Model>
> {
  // To avoid table creation
  /*static async sync(): Promise<any> {
      return Promise.resolve();
    }*/

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static associate(connection: Sequelize) {}

  declare id: string;
  declare name: string;
  declare email: string;
  declare password: string;
  declare lang_code: string;
  declare roles: string[];
}

export default (sequelize: Sequelize) => {
  AuthUser_Model.init(
    {
      id: {
        type: new DataTypes.UUID(),
        primaryKey: true,
      },

      name: {
        type: DataTypes.STRING,
      },

      email: {
        type: DataTypes.STRING,
        allowNull: false,
      },

      password: {
        type: DataTypes.STRING,
        allowNull: false,
      },

      lang_code: {
        type: DataTypes.STRING(2),
        allowNull: false,
        defaultValue: "es",
      },

      roles: {
        type: DataTypes.STRING,
        allowNull: false,
        defaultValue: USER_ROLES.ROLE_USER,
        get(this: AuthUser_Model): string[] {
          const rawValue = this.getDataValue("roles") as any;
          return String(rawValue).split(";");
        },
        set(this: AuthUser_Model, value: string[]) {
          const rawValue = value.join(";") as any;
          this.setDataValue("roles", rawValue);
        },
      },
    },
    {
      sequelize,
      tableName: "users",

      paranoid: true, // softs deletes
      timestamps: true,
      //version: true,

      createdAt: "created_at",
      updatedAt: "updated_at",
      deletedAt: "deleted_at",

      indexes: [{ name: "email_idx", fields: ["email"], unique: true }],
    }
  );

  return AuthUser_Model;
};
