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

// Get All Purchases
router.get('/', authenticateToken, isAdmin, async (req, res) => {
    try {
        const purchases = await Purchase.findAll({
            include: [{
                model: PurchaseItem,
                include: [{ model: Book, attributes: ['title', 'isbn'] }]
            }],
            order: [['created_at', 'DESC']]
        });

        // Format for frontend
        const formatted = purchases.map(p => {
            const itemsCount = p.PurchaseItems ? p.PurchaseItems.reduce((acc, item) => acc + item.quantity, 0) : 0;
            return {
                id: p.id,
                date: p.createdAt,
                supplier: p.supplier_name,
                items: itemsCount,
                total: parseFloat(p.total_cost),
                status: 'Received', // Default status for now
                details: p.PurchaseItems
            };
        });

        res.json(formatted);
    } catch (error) {
        console.error("Fetch purchases error:", error);
        res.status(500).json({ message: 'Server error' });
    }
});

// Create New Purchase
router.post('/', authenticateToken, isAdmin, async (req, res) => {
    const t = await sequelize.transaction();
    try {
        const { supplier_name, items } = req.body; // items: [{ book_id, quantity, cost_price }]

        if (!items || items.length === 0) {
            return res.status(400).json({ message: 'No items in purchase' });
        }

        // Calculate total cost
        const total_cost = items.reduce((sum, item) => sum + (item.quantity * item.cost_price), 0);

        // 1. Create Purchase
        const purchase = await Purchase.create({
            supplier_name,
            total_cost
        }, { transaction: t });

        // 2. Create Purchase Items & Update Stock
        for (const item of items) {
            await PurchaseItem.create({
                purchase_id: purchase.id,
                book_id: item.book_id,
                quantity: item.quantity,
                cost_price: item.cost_price
            }, { transaction: t });

            // Update Book Stock
            const book = await Book.findByPk(item.book_id, { transaction: t });
            if (book) {
                await book.update({
                    stock: book.stock + parseInt(item.quantity)
                }, { transaction: t });
            }
        }

        await t.commit();
        res.status(201).json({ message: 'Purchase recorded and stock updated', purchaseId: purchase.id });

    } catch (error) {
        await t.rollback();
        console.error("Create purchase error:", error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

module.exports = router;
