"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 multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const index_1 = require("../index");
const auth_1 = require("../middleware/auth");
const router = (0, express_1.Router)();
// Use carla-skin-clinic-web root uploads/articles as upload directory
// __dirname is backend/src/routes, go up 3 levels to carla-skin-clinic-web root
const projectRoot = path_1.default.join(__dirname, '..', '..', '..');
const articlesDir = path_1.default.join(projectRoot, 'uploads', 'articles');
if (!fs_1.default.existsSync(articlesDir))
    fs_1.default.mkdirSync(articlesDir, { recursive: true });
// Multer for image upload
const storage = multer_1.default.diskStorage({
    destination: (req, file, cb) => cb(null, articlesDir),
    filename: (req, file, cb) => {
        const ext = path_1.default.extname(file.originalname);
        cb(null, `article-${Date.now()}${ext}`);
    },
});
const upload = (0, multer_1.default)({
    storage,
    limits: { fileSize: 5 * 1024 * 1024 },
    fileFilter: (req, file, cb) => {
        cb(null, /jpeg|jpg|png|gif|webp/.test(path_1.default.extname(file.originalname).toLowerCase()));
    },
});
// GET /api/articles - Public: published only. Admin: ?all=true returns all
router.get('/', async (req, res) => {
    try {
        const showAll = req.query.all === 'true';
        const articles = await index_1.prisma.article.findMany({
            where: showAll ? undefined : { status: 'published' },
            orderBy: { createdAt: 'desc' },
        });
        res.json(articles);
    }
    catch (error) {
        res.status(500).json({ message: 'Gagal mengambil artikel' });
    }
});
// GET /api/articles/:slug - Public: Get single article by slug
router.get('/:slug', async (req, res) => {
    try {
        const article = await index_1.prisma.article.findUnique({ where: { slug: req.params.slug } });
        if (!article)
            return res.status(404).json({ message: 'Artikel tidak ditemukan' });
        res.json(article);
    }
    catch (error) {
        res.status(500).json({ message: 'Gagal mengambil artikel' });
    }
});
// POST /api/articles - Admin: Create new article
router.post('/', auth_1.authMiddleware, upload.single('image'), async (req, res) => {
    try {
        const { title, slug, content, excerpt, category, status, tags, metaTitle, metaDesc } = req.body;
        const image = req.file ? `/uploads/articles/${req.file.filename}` : undefined;
        if (!title || !content || !category) {
            return res.status(400).json({ message: 'Title, content, dan category diperlukan' });
        }
        // Get author from token
        const user = await index_1.prisma.user.findUnique({ where: { id: req.userId } });
        const author = user?.fullName || user?.username || 'Admin';
        const finalSlug = slug || title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
        const article = await index_1.prisma.article.create({
            data: {
                title, slug: finalSlug, content, excerpt, category, author, image,
                status: status || 'draft',
                tags: tags || null,
                metaTitle: metaTitle || null,
                metaDesc: metaDesc || null,
            }
        });
        res.status(201).json(article);
    }
    catch (error) {
        if (error.code === 'P2002')
            return res.status(400).json({ message: 'Slug sudah ada' });
        res.status(500).json({ message: 'Gagal membuat artikel' });
    }
});
// PUT /api/articles/:id - Admin: Update article
router.put('/:id', auth_1.authMiddleware, upload.single('image'), async (req, res) => {
    try {
        const data = { ...req.body };
        if (req.file)
            data.image = `/uploads/articles/${req.file.filename}`;
        delete data.readTime;
        delete data.id;
        delete data.author;
        delete data.createdAt;
        delete data.updatedAt;
        const article = await index_1.prisma.article.update({ where: { id: parseInt(req.params.id) }, data });
        res.json(article);
    }
    catch (error) {
        if (error.code === 'P2002')
            return res.status(400).json({ message: 'Slug sudah ada' });
        res.status(500).json({ message: 'Gagal mengupdate artikel' });
    }
});
// DELETE /api/articles/:id - Admin: Delete article
router.delete('/:id', auth_1.authMiddleware, async (req, res) => {
    try {
        await index_1.prisma.article.delete({ where: { id: parseInt(req.params.id) } });
        res.json({ message: 'Artikel berhasil dihapus' });
    }
    catch (error) {
        res.status(500).json({ message: 'Gagal menghapus artikel' });
    }
});
exports.default = router;
//# sourceMappingURL=articles.js.map