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

// Get Active Vouchers (Public or Auth?)
// Let's make it public for now to list available vouchers
router.get('/vouchers', async (req, res) => {
    try {
        const vouchers = await Voucher.findAll({
            where: { status: 'Active' }
        });
        res.json(vouchers);
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// Verify Voucher
router.post('/vouchers/verify', async (req, res) => {
    try {
        const { code, totalAmount } = req.body;
        const voucher = await Voucher.findOne({ where: { code } });

        if (!voucher) {
            return res.json({ valid: false, message: 'Voucher invalid atau tidak ditemukan' });
        }
        if (voucher.status !== 'Active') {
            return res.json({ valid: false, message: 'Voucher tidak aktif' });
        }
        if (voucher.minPurchase > totalAmount) {
            return res.json({ valid: false, message: `Minimal pembelian Rp ${parseInt(voucher.minPurchase).toLocaleString('id-ID')}` });
        }
        if (new Date(voucher.expiryDate) < new Date()) {
            return res.json({ valid: false, message: 'Voucher sudah kadaluarsa' });
        }

        // Calculate discount
        let discountAmount = 0;
        if (voucher.type === 'Percentage') {
            discountAmount = (totalAmount * voucher.discount) / 100;
            if (voucher.maxDiscount) {
                discountAmount = Math.min(discountAmount, voucher.maxDiscount);
            }
        } else {
            discountAmount = voucher.discount;
        }

        res.json({
            valid: true,
            discount: discountAmount,
            voucher
        });
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// Admin: Create Voucher
// Admin: Create Voucher
router.post('/vouchers', authenticateToken, isAdmin, async (req, res) => {
    try {
        const voucher = await Voucher.create(req.body);
        res.status(201).json(voucher);
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// Admin: Update Voucher
router.put('/vouchers/:id', authenticateToken, isAdmin, async (req, res) => {
    try {
        const { id } = req.params;
        const voucher = await Voucher.findByPk(id);
        if (!voucher) return res.status(404).json({ message: 'Voucher not found' });
        
        await voucher.update(req.body);
        res.json(voucher);
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// Admin: Delete Voucher
router.delete('/vouchers/:id', authenticateToken, isAdmin, async (req, res) => {
    try {
        const { id } = req.params;
        const voucher = await Voucher.findByPk(id);
        if (!voucher) return res.status(404).json({ message: 'Voucher not found' });
        
        await voucher.destroy();
        res.json({ message: 'Voucher deleted' });
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// Testimonials (Mock for now, can be a model if we want to scale)
router.get('/testimonials', (req, res) => {
    const testimonials = [
        {
            id: 1,
            name: "Budi Santoso",
            role: "Mahasiswa",
            text: "Belanja buku di Nalar sangat mudah dan cepat. Pengiriman tepat waktu dan pelayanan sangat memuaskan!",
            avatar: "https://i.pravatar.cc/150?u=Budi",
            rating: 5
        },
        {
            id: 2,
            name: "Siti Rahma",
            role: "Guru",
            text: "Koleksi bukunya lengkap dan harganya terjangkau. Sudah langganan di sini untuk kebutuhan mengajar.",
            avatar: "https://i.pravatar.cc/150?u=Siti",
            rating: 5
        },
        {
            id: 3,
            name: "Andi Wijaya",
            role: "Penulis",
            text: "Platform yang sangat mendukung literasi Indonesia. Senang bisa menemukan buku-buku langka di sini.",
            avatar: "https://i.pravatar.cc/150?u=Andi",
            rating: 4
        }
    ];
    res.json(testimonials);
});

module.exports = router;
