import { DataTypes, InferAttributes, InferCreationAttributes, Model, Sequelize } from "sequelize";

export type AuthUserCreationAttributes = InferCreationAttributes<AuthUserModel>;

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

  declare id: string;
  declare username: string;
  declare email: string;
  declare hash_password: string;
  declare roles: string[];
}

export default (sequelize: Sequelize) => {
  AuthUserModel.init(
    {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
      },
      username: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      email: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      hash_password: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      roles: {
        type: DataTypes.STRING,
        allowNull: false,
        defaultValue: "USER",
        get(this: AuthUserModel): string[] {
          const rawValue = this.getDataValue("roles") as any;
          return String(rawValue).split(";");
        },
        set(this: AuthUserModel, value: string[]) {
          const rawValue = value.join(";") as any;
          this.setDataValue("roles", rawValue);
        },
      },
    },
    {
      sequelize,
      tableName: "users",
      paranoid: true, // softs deletes
      timestamps: true,

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

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

      whereMergeStrategy: "and", // <- cómo tratar el merge de un scope

      defaultScope: {},

      scopes: {},
    }
  );
  return AuthUserModel;
};
