const express = require('express');
const { User } = require('../models');
const { authenticateToken, isAdmin } = require('../middleware/auth');
const router = express.Router();

// Admin: Get All Users
router.get('/', authenticateToken, isAdmin, async (req, res) => {
    try {
        const users = await User.findAll({
            attributes: { exclude: ['password'] }
        });
        res.json(users);
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Configure Multer
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const dir = path.join(__dirname, '../uploads/profiles');
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        cb(null, dir);
    },
    filename: function (req, file, cb) {
        cb(null, 'profile-' + Date.now() + path.extname(file.originalname));
    }
});

const upload = multer({
    storage: storage,
    limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
    fileFilter: (req, file, cb) => {
        if (file.mimetype.startsWith('image/')) {
            cb(null, true);
        } else {
            cb(new Error('Only images are allowed'));
        }
    }
});

// Update Profile
router.put('/profile', authenticateToken, upload.single('image'), async (req, res) => {
    try {
        const { username, name, phone, address, dob, bio } = req.body;
        const user = await User.findByPk(req.user.id);

        if (!user) return res.status(404).json({ message: 'User not found' });

        if (username && username !== user.username) {
            const existingUser = await User.findOne({ where: { username } });
            if (existingUser) {
                return res.status(400).json({ message: 'Username sudah digunakan' });
            }
            user.username = username;
        }

        user.name = name || user.name;
        user.phone = phone || user.phone;
        user.address = address || user.address;
        if (dob !== undefined) user.dob = dob;
        if (bio !== undefined) user.bio = bio;

        if (req.file) {
            // Construct URL. stored path is uploads/profiles/filename.
            // Server serves /uploads. So URL should be {BASE_URL}/uploads/profiles/filename
            // Assuming simplified relative path storage or full URL if domain known.
            // For now store relative path 'http://localhost:5000/uploads/profiles/' + filename
            // Ideally we store relative and prepend domain on frontend, OR store full URL.
            // Existing seed uses full URL. Let's stick to full URL for consistency.
            const baseUrl = `${req.protocol}://${req.get('host')}`;
            user.image = `${baseUrl}/uploads/profiles/${req.file.filename}`;
        }

        await user.save();

        res.json({
            message: 'Profile updated successfully',
            user: {
                id: user.id,
                username: user.username,
                name: user.name,
                email: user.email,
                role: user.role,
                phone: user.phone,
                address: user.address,
                dob: user.dob,
                bio: user.bio,
                avatar: user.image
            }
        });
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// Change Password
router.put('/change-password', authenticateToken, async (req, res) => {
    try {
        const { currentPassword, newPassword } = req.body;
        const user = await User.findByPk(req.user.id);
        const bcrypt = require('bcryptjs');

        if (!user) return res.status(404).json({ message: 'User not found' });

        const isMatch = await bcrypt.compare(currentPassword, user.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Password saat ini salah' });
        }

        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(newPassword, salt);
        await user.save();

        res.json({ message: 'Password berhasil diubah' });
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// Admin: Update User Status
router.put('/:id/status', authenticateToken, isAdmin, async (req, res) => {
    try {
        const { status } = req.body;
        const user = await User.findByPk(req.params.id);
        if (!user) return res.status(404).json({ message: 'User not found' });

        user.status = status;
        await user.save();
        res.json(user);
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// Admin: Update User (Role, Status, etc)
router.put('/:id', authenticateToken, isAdmin, async (req, res) => {
    try {
        const { name, email, role, phone, address, status } = req.body;
        const user = await User.findByPk(req.params.id);

        if (!user) return res.status(404).json({ message: 'User not found' });

        // Optional: specific validations like unique email if changed

        if (name) user.name = name;
        if (email) user.email = email; // Be careful with unique constraints
        if (role) user.role = role;
        if (phone) user.phone = phone;
        if (address) user.address = address;
        if (status) user.status = status;

        await user.save();

        res.json({
            message: 'User updated successfully',
            user: {
                id: user.id,
                name: user.name,
                email: user.email,
                role: user.role,
                status: user.status,
                phone: user.phone,
                address: user.address,
                avatar: user.image
            }
        });
    } catch (error) {
        console.error("Update User Error:", error);
        res.status(500).json({ message: 'Server error' });
    }
});

// Admin: Delete User
router.delete('/:id', authenticateToken, isAdmin, async (req, res) => {
    try {
        const user = await User.findByPk(req.params.id);
        if (!user) return res.status(404).json({ message: 'User not found' });

        await user.destroy();
        res.json({ message: 'User deleted successfully' });
    } catch (error) {
        console.error("Delete User Error:", error);
        res.status(500).json({ message: 'Server error' });
    }
});

module.exports = router;
