"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 project root public/images/promo as upload directory
// __dirname is backend/src/routes, go up 3 levels to get to carla-skin-clinic-web root
const projectRoot = path_1.default.join(__dirname, '..', '..', '..');
const promosDir = path_1.default.join(projectRoot, 'public', 'images', 'promo');
// Ensure directory exists
if (!fs_1.default.existsSync(promosDir)) {
    fs_1.default.mkdirSync(promosDir, { recursive: true });
}
const storage = multer_1.default.diskStorage({
    destination: (req, file, cb) => cb(null, promosDir),
    filename: (req, file, cb) => {
        const ext = path_1.default.extname(file.originalname);
        cb(null, `promo-${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/promos - Get all promos
router.get('/', async (req, res) => {
    try {
        const promos = await index_1.prisma.promo.findMany({
            orderBy: { createdAt: 'desc' },
        });
        res.json(promos);
    }
    catch (error) {
        console.error('Error fetching promos:', error);
        res.status(500).json({ message: 'Gagal mengambil promo' });
    }
});
// GET /api/promos/featured - Get featured promos
router.get('/featured', async (req, res) => {
    try {
        const promos = await index_1.prisma.promo.findMany({
            where: { featured: true, isActive: true },
            orderBy: { createdAt: 'desc' },
        });
        res.json(promos);
    }
    catch (error) {
        console.error('Error fetching featured promos:', error);
        res.status(500).json({ message: 'Gagal mengambil featured promo' });
    }
});
// GET /api/promos/:slug - Get promo by slug
router.get('/:slug', async (req, res) => {
    try {
        const promo = await index_1.prisma.promo.findUnique({
            where: { slug: req.params.slug },
        });
        if (!promo) {
            return res.status(404).json({ message: 'Promo tidak ditemukan' });
        }
        res.json(promo);
    }
    catch (error) {
        console.error('Error fetching promo:', error);
        res.status(500).json({ message: 'Gagal mengambil promo' });
    }
});
// POST /api/promos - Create new promo
router.post('/', auth_1.authMiddleware, upload.single('image'), async (req, res) => {
    try {
        const { title, slug, description, promoPrice, normalPrice, discount, periodStart, periodEnd, category, featured, isActive } = req.body;
        if (!title) {
            return res.status(400).json({ message: 'Title diperlukan' });
        }
        const image = req.file ? `/images/promo/${req.file.filename}` : undefined;
        const promo = await index_1.prisma.promo.create({
            data: {
                title,
                slug: slug || title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''),
                description,
                promoPrice: promoPrice || null,
                normalPrice,
                discount,
                periodStart: periodStart ? new Date(periodStart) : null,
                periodEnd: periodEnd ? new Date(periodEnd) : null,
                category: category || 'general',
                image,
                featured: featured === 'true' || featured === true,
                isActive: isActive !== undefined ? isActive === 'true' || isActive === true : true
            }
        });
        res.status(201).json({ message: 'Promo berhasil dibuat', ...promo });
    }
    catch (error) {
        console.error('Error creating promo:', error);
        if (error.code === 'P2002') {
            return res.status(400).json({ message: 'Slug sudah ada' });
        }
        res.status(500).json({ message: 'Gagal membuat promo' });
    }
});
// PUT /api/promos/:id - Update promo
router.put('/:id', auth_1.authMiddleware, upload.single('image'), async (req, res) => {
    try {
        const { title, slug, description, promoPrice, normalPrice, discount, periodStart, periodEnd, category, featured, isActive } = req.body;
        const data = { ...req.body };
        if (req.file)
            data.image = `/images/promo/${req.file.filename}`;
        if (data.featured !== undefined)
            data.featured = data.featured === 'true' || data.featured === true;
        if (data.isActive !== undefined)
            data.isActive = data.isActive === 'true' || data.isActive === true;
        // Parse period dates
        if (periodStart !== undefined)
            data.periodStart = periodStart ? new Date(periodStart) : null;
        if (periodEnd !== undefined)
            data.periodEnd = periodEnd ? new Date(periodEnd) : null;
        // Generate slug if provided or keep existing
        if (slug && slug !== '') {
            data.slug = slug;
        }
        const promo = await index_1.prisma.promo.update({
            where: { id: parseInt(req.params.id) },
            data
        });
        res.json({ message: 'Promo berhasil diupdate', ...promo });
    }
    catch (error) {
        console.error('Error updating promo:', error);
        if (error.code === 'P2002') {
            return res.status(400).json({ message: 'Slug sudah ada' });
        }
        res.status(500).json({ message: 'Gagal mengupdate promo' });
    }
});
// DELETE /api/promos/:id - Delete promo
router.delete('/:id', auth_1.authMiddleware, async (req, res) => {
    try {
        await index_1.prisma.promo.delete({ where: { id: parseInt(req.params.id) } });
        res.json({ message: 'Promo berhasil dihapus' });
    }
    catch (error) {
        console.error('Error deleting promo:', error);
        res.status(500).json({ message: 'Gagal menghapus promo' });
    }
});
exports.default = router;
//# sourceMappingURL=promos.js.map