const { Sequelize } = require('sequelize');
const db = require('../config/database');

const { DataTypes } = Sequelize;

const Users = db.define('users', {
    name: {
        type: DataTypes.STRING,
        allowNull: false
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
    },
    password: {
        type: DataTypes.STRING,
        allowNull: false
    },

    // 🔹 NEW: role user
    // MAIN = akun utama, SUB = sub-account
    role: {
        type: DataTypes.STRING,
        allowNull: false,
        defaultValue: 'MAIN'
    },

    // 🔹 NEW: relasi parent
    parent_user_id: {
        type: DataTypes.INTEGER,
        allowNull: true
    },

    // 🔹 NEW: bisa nonaktifkan sub-account tanpa hapus data
    is_active: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: true
    }
}, {
    freezeTableName: true
});

// Optional: asosiasi self-reference
Users.hasMany(Users, {
    as: 'subAccounts',
    foreignKey: 'parent_user_id'
});

Users.belongsTo(Users, {
    as: 'parent',
    foreignKey: 'parent_user_id'
});

module.exports = Users;
