"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const argon2_1 = __importDefault(require("argon2"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const index_1 = require("../index");
const auth_1 = require("../middleware/auth");
const router = (0, express_1.Router)();
const JWT_SECRET = process.env.JWT_SECRET || 'carla-skin-clinic-secret-key-2026';
// Password validation
const isValidPassword = (pwd) => /[A-Z]/.test(pwd) && /[0-9]/.test(pwd) && /[!@#$%^&*(),.?":{}|<>_\-]/.test(pwd) && pwd.length >= 8;
// Multer
const storage = multer_1.default.diskStorage({
    destination: (req, file, cb) => cb(null, 'uploads/profiles'),
    filename: (req, file, cb) => {
        const ext = path_1.default.extname(file.originalname);
        cb(null, `profile-${Date.now()}${ext}`);
    },
});
const upload = (0, multer_1.default)({
    storage,
    limits: { fileSize: 5 * 1024 * 1024 },
    fileFilter: (req, file, cb) => {
        const allowed = /jpeg|jpg|png|gif|webp/;
        cb(null, allowed.test(path_1.default.extname(file.originalname).toLowerCase()));
    },
});
const sanitizeUser = (user) => ({
    id: user.id, username: user.username, role: user.role,
    fullName: user.fullName, photo: user.photo, createdAt: user.createdAt, updatedAt: user.updatedAt,
});
// POST /api/auth/login
router.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;
        if (!username || !password)
            return res.status(400).json({ message: 'Username dan password diperlukan' });
        const user = await index_1.prisma.user.findUnique({ where: { username } });
        if (!user || !(await argon2_1.default.verify(user.password, password))) {
            return res.status(401).json({ message: 'Username atau password salah' });
        }
        const token = jsonwebtoken_1.default.sign({ userId: user.id, role: user.role }, JWT_SECRET, { expiresIn: '24h' });
        res.json({ message: 'Login berhasil', token, user: sanitizeUser(user) });
    }
    catch (error) {
        res.status(500).json({ message: 'Terjadi kesalahan server' });
    }
});
// GET /api/auth/me
router.get('/me', auth_1.authMiddleware, async (req, res) => {
    try {
        const user = await index_1.prisma.user.findUnique({ where: { id: req.userId } });
        if (!user)
            return res.status(404).json({ message: 'User tidak ditemukan' });
        res.json(sanitizeUser(user));
    }
    catch (error) {
        res.status(500).json({ message: 'Gagal mengambil data user' });
    }
});
// PUT /api/auth/profile - Update profile (name, photo) & set new password
router.put('/profile', auth_1.authMiddleware, upload.single('photo'), async (req, res) => {
    try {
        const { fullName, newPassword } = req.body;
        const user = await index_1.prisma.user.findUnique({ where: { id: req.userId } });
        if (!user)
            return res.status(404).json({ message: 'User tidak ditemukan' });
        const data = {};
        if (fullName !== undefined)
            data.fullName = fullName;
        if (req.file)
            data.photo = `/uploads/profiles/${req.file.filename}`;
        if (newPassword) {
            if (!isValidPassword(newPassword)) {
                return res.status(400).json({ message: 'Password harus minimal 8 karakter, kombinasi huruf besar, angka, dan simbol' });
            }
            data.password = await argon2_1.default.hash(newPassword);
        }
        const updated = await index_1.prisma.user.update({ where: { id: req.userId }, data });
        res.json({ message: 'Profil berhasil diupdate', user: sanitizeUser(updated) });
    }
    catch (error) {
        res.status(500).json({ message: 'Gagal mengupdate profil' });
    }
});
// POST /api/auth/register - Admin only
router.post('/register', auth_1.authMiddleware, upload.single('photo'), async (req, res) => {
    try {
        if (req.userRole !== 'admin')
            return res.status(403).json({ message: 'Hanya admin yang bisa membuat user baru' });
        const { username, password, fullName, role } = req.body;
        if (!username || !password)
            return res.status(400).json({ message: 'Username dan password diperlukan' });
        if (!isValidPassword(password)) {
            return res.status(400).json({ message: 'Password harus minimal 8 karakter, kombinasi huruf besar, angka, dan simbol' });
        }
        const existing = await index_1.prisma.user.findUnique({ where: { username } });
        if (existing)
            return res.status(400).json({ message: 'Username sudah terdaftar' });
        const hashedPassword = await argon2_1.default.hash(password);
        const photo = req.file ? `/uploads/profiles/${req.file.filename}` : undefined;
        const user = await index_1.prisma.user.create({
            data: { username, password: hashedPassword, fullName, photo, role: role || 'editor' }
        });
        res.status(201).json({ message: 'User berhasil dibuat', user: sanitizeUser(user) });
    }
    catch (error) {
        res.status(500).json({ message: 'Gagal membuat user' });
    }
});
// GET /api/auth/users
router.get('/users', auth_1.authMiddleware, async (req, res) => {
    try {
        if (req.userRole !== 'admin')
            return res.status(403).json({ message: 'Hanya admin' });
        const users = await index_1.prisma.user.findMany({ orderBy: { createdAt: 'desc' } });
        res.json(users.map(sanitizeUser));
    }
    catch (error) {
        res.status(500).json({ message: 'Gagal mengambil data users' });
    }
});
// DELETE /api/auth/users/:id
router.delete('/users/:id', auth_1.authMiddleware, async (req, res) => {
    try {
        if (req.userRole !== 'admin')
            return res.status(403).json({ message: 'Hanya admin' });
        const targetId = parseInt(req.params.id);
        if (targetId === req.userId)
            return res.status(400).json({ message: 'Tidak bisa menghapus diri sendiri' });
        await index_1.prisma.user.delete({ where: { id: targetId } });
        res.json({ message: 'User berhasil dihapus' });
    }
    catch (error) {
        res.status(500).json({ message: 'Gagal menghapus user' });
    }
});
// PUT /api/auth/users/:id
router.put('/users/:id', auth_1.authMiddleware, upload.single('photo'), async (req, res) => {
    try {
        if (req.userRole !== 'admin')
            return res.status(403).json({ message: 'Hanya admin' });
        const { fullName, role, newPassword, username } = req.body;
        const data = { fullName, role };
        if (req.file)
            data.photo = `/uploads/profiles/${req.file.filename}`;
        if (username)
            data.username = username;
        if (newPassword) {
            if (!isValidPassword(newPassword)) {
                return res.status(400).json({ message: 'Password harus minimal 8 karakter, kombinasi huruf besar, angka, dan simbol' });
            }
            data.password = await argon2_1.default.hash(newPassword);
        }
        const user = await index_1.prisma.user.update({ where: { id: parseInt(req.params.id) }, data });
        res.json({ message: 'User berhasil diupdate', user: sanitizeUser(user) });
    }
    catch (error) {
        if (error.code === 'P2002')
            return res.status(400).json({ message: 'Username sudah digunakan' });
        res.status(500).json({ message: 'Gagal mengupdate user' });
    }
});
exports.default = router;
//# sourceMappingURL=auth.js.map