const Users = require('../models/UserModel');
const bcrypt = require('bcrypt');
const { isMainAccount } = require('../utils/userScope');

exports.getSubAccounts = async (req, res) => {
    try {
        const isMain = await isMainAccount(req.userId);
        if (!isMain) {
            return res.status(403).json({ msg: "Hanya akun utama yang dapat melihat sub-account" });
        }

        const subs = await Users.findAll({
            where: {
                parent_user_id: req.userId
            },
            attributes: ['id', 'name', 'email', 'role', 'parent_user_id', 'is_active', 'createdAt', 'updatedAt']
        });

        return res.json(subs);
    } catch (error) {
        console.log(error);
        return res.status(500).json({ msg: "Gagal mengambil data sub-account" });
    }
};

exports.createSubAccount = async (req, res) => {
    const { name, email, password, confPassword } = req.body;

    try {
        const isMain = await isMainAccount(req.userId);
        if (!isMain) {
            return res.status(403).json({ msg: "Hanya akun utama yang dapat membuat sub-account" });
        }

        if (!name || !email || !password || !confPassword) {
            return res.status(400).json({ msg: "Nama, email, password, dan konfirmasi password wajib diisi" });
        }

        if (password !== confPassword) {
            return res.status(400).json({ msg: "Password dan konfirmasi password tidak sama" });
        }

        const existing = await Users.findOne({ where: { email } });
        if (existing) {
            return res.status(400).json({ msg: "Email sudah terdaftar" });
        }

        const salt = await bcrypt.genSalt();
        const hashPassword = await bcrypt.hash(password, salt);

        const subUser = await Users.create({
            name,
            email,
            password: hashPassword,
            role: 'SUB',
            parent_user_id: req.userId,
            is_active: true
        });

        return res.status(201).json({
            msg: "Sub-account berhasil dibuat",
            data: {
                id: subUser.id,
                name: subUser.name,
                email: subUser.email,
                role: subUser.role,
                parent_user_id: subUser.parent_user_id,
                is_active: subUser.is_active
            }
        });
    } catch (error) {
        console.log(error);
        return res.status(500).json({ msg: "Gagal membuat sub-account" });
    }
};

exports.updateSubAccount = async (req, res) => {
    const { id } = req.params;
    const { name, is_active } = req.body;

    try {
        const isMain = await isMainAccount(req.userId);
        if (!isMain) {
            return res.status(403).json({ msg: "Hanya akun utama yang dapat mengubah sub-account" });
        }

        const sub = await Users.findOne({
            where: {
                id: id,
                parent_user_id: req.userId
            }
        });

        if (!sub) {
            return res.status(404).json({ msg: "Sub-account tidak ditemukan" });
        }

        if (name !== undefined) {
            sub.name = name;
        }

        if (is_active !== undefined) {
            sub.is_active = !!is_active;
        }

        await sub.save();

        return res.json({ msg: "Sub-account berhasil diupdate" });
    } catch (error) {
        console.log(error);
        return res.status(500).json({ msg: "Gagal mengupdate sub-account" });
    }
};

exports.deactivateSubAccount = async (req, res) => {
    const { id } = req.params;

    try {
        const isMain = await isMainAccount(req.userId);
        if (!isMain) {
            return res.status(403).json({ msg: "Hanya akun utama yang dapat menonaktifkan sub-account" });
        }

        const sub = await Users.findOne({
            where: {
                id: id,
                parent_user_id: req.userId
            }
        });

        if (!sub) {
            return res.status(404).json({ msg: "Sub-account tidak ditemukan" });
        }

        sub.is_active = false;
        await sub.save();

        return res.json({
            msg: "Sub-account dinonaktifkan",
            data: {
                id: sub.id,
                is_active: sub.is_active
            }
        });
    } catch (error) {
        console.log(error);
        return res.status(500).json({ msg: "Gagal menonaktifkan sub-account" });
    }
};
