"use strict";
const { Model, DataTypes } = require("sequelize");

module.exports = (sequelize) => {
  class User extends Model {
    static associate(models) {
      this.belongsTo(models.Branch, {foreignKey: 'branch_id', as: 'branch', onDelete: 'CASCADE'})
    }
  }

  User.init({
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      allowNull: false,
      primaryKey: true,
    },
    branch_id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      allowNull: false,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: true
    },
    role: {
      type: DataTypes.ENUM('admin', 'user'),
      allowNull: true,
      defaultValue: 'user'
    },
    email: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: false,
      validate: {
        isEmail: true,
      },
    },

    avatar_url: {
      type: DataTypes.STRING,
      allowNull: true
    },

    phone: {
      type: DataTypes.STRING,
      allowNull: true,
      unique: true,
      validate: {
        is: {
          args: /^\+?[0-9\s\-]{6,20}$/,
          msg: 'Format nomor telepon tidak valid',
        },
        len: {
          args: [6, 15],
          msg: "Nomor telepon maksimal 15 karakter"
        }
      }
    },
    password: {
      type: DataTypes.STRING,
      allowNull: true
    },


    provider_id: {
      type: DataTypes.STRING,
      allowNull: true
    },
    login_via: {
      type: DataTypes.STRING,
      defaultValue: 'EMAIL',
    },
    google_id: {
      type: DataTypes.STRING,
    },
    is_suspended: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    birth: {
      type: DataTypes.DATE,
      allowNull: true
    },
    last_login: {
      type: DataTypes.DATE,
    },
    is_first_login: {
      type: DataTypes.BOOLEAN,
      defaultValue: true
    },
    created_at: {
      type: DataTypes.DATE,
    },
    updated_at: {
      type: DataTypes.DATE,
    },
    deleted_at: {
      type: DataTypes.DATE,
    },
  },
    {
      sequelize,
      modelName: "User",
      tableName: "core_users",
      timestamps: true,
      createdAt: "created_at",
      updatedAt: "updated_at",
      deletedAt: "deleted_at",
      paranoid: true,
    });

  return User;
};
