"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getKitchenOrders = exports.updateOrderStatus = exports.settleTable = exports.getOrders = exports.createOrder = exports.deleteTable = exports.updateTable = exports.createTable = exports.getTables = exports.deleteFloor = exports.updateFloor = exports.createFloor = exports.getFloors = void 0;
const Restaurant_1 = require("../models/Restaurant");
// --- Floos ---
const getFloors = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const floors = yield Restaurant_1.Floor.find({});
        res.json(floors);
    }
    catch (error) {
        res.status(500).json({ message: 'Error fetching floors', error });
    }
});
exports.getFloors = getFloors;
const createFloor = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id, name } = req.body;
        const newFloor = new Restaurant_1.Floor({ id, name });
        yield newFloor.save();
        res.status(201).json(newFloor);
    }
    catch (error) {
        res.status(500).json({ message: 'Error creating floor', error });
    }
});
exports.createFloor = createFloor;
const updateFloor = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        const { name } = req.body;
        const updatedFloor = yield Restaurant_1.Floor.findOneAndUpdate({ id: Number(id) }, { name }, { new: true });
        res.json(updatedFloor);
    }
    catch (error) {
        res.status(500).json({ message: 'Error updating floor', error });
    }
});
exports.updateFloor = updateFloor;
const deleteFloor = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        yield Restaurant_1.Floor.findOneAndDelete({ id: Number(id) });
        // Also delete tables on this floor?
        yield Restaurant_1.Table.deleteMany({ floorId: Number(id) });
        res.json({ message: 'Floor deleted' });
    }
    catch (error) {
        res.status(500).json({ message: 'Error deleting floor', error });
    }
});
exports.deleteFloor = deleteFloor;
// --- Tables ---
const getTables = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const tables = yield Restaurant_1.Table.find({});
        // Map _id to id if frontend needs number id, but frontend seems to use number id.
        // We might need to handle the ID difference. 
        // For simple sync, let's just return what we have.
        // Frontend uses number IDs. We should probably stick to number IDs for simplicity if we want to match exactly, 
        // OR update frontend to use string _id.
        // Given existing frontend `initialTables` has `id: number`, I should probably also store `id: number` in TableSchema or just map it.
        // Let's modify the response to include `id` as `_id` or just pass `_id`.
        // The frontend expects `id`. 
        // Let's just update the Table Schema to also have a custom `id` field like Floor for consistency with existing frontend logic?
        // OR simpler: modify frontend to use _id.
        // modifying frontend to use _id is better long term.
        // But for now, to minimize friction, I will fetch tables.
        res.json(tables);
    }
    catch (error) {
        res.status(500).json({ message: 'Error fetching tables', error });
    }
});
exports.getTables = getTables;
const createTable = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const tableData = req.body;
        // if tableData has id, we can store it if we added it to schema.
        // Let's assume we want to store everything.
        const newTable = new Restaurant_1.Table(tableData);
        yield newTable.save();
        res.status(201).json(newTable);
    }
    catch (error) {
        res.status(500).json({ message: 'Error creating table', error });
    }
});
exports.createTable = createTable;
const updateTable = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        // This id is likely the Mongoose _id if we switch to it, or our custom id.
        // If frontend sends custom id number:
        const updates = req.body;
        // If we are using custom `id` field:
        const updatedTable = yield Restaurant_1.Table.findOneAndUpdate({ id: Number(id) }, updates, { new: true });
        // If we use _id:
        // const updatedTable = await Table.findByIdAndUpdate(id, updates, { new: true });
        res.json(updatedTable);
    }
    catch (error) {
        res.status(500).json({ message: 'Error updating table', error });
    }
});
exports.updateTable = updateTable;
const deleteTable = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        yield Restaurant_1.Table.findOneAndDelete({ id: Number(id) });
        res.json({ message: 'Table deleted' });
    }
    catch (error) {
        res.status(500).json({ message: 'Error deleting table', error });
    }
});
exports.deleteTable = deleteTable;
// Special batch update for positions if needed, but updateTable works fine.
// --- Orders ---
const Order_1 = __importDefault(require("../models/Order"));
const createOrder = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const orderData = req.body;
        const newOrder = new Order_1.default(orderData);
        yield newOrder.save();
        res.status(201).json(newOrder);
    }
    catch (error) {
        console.error("Error creating order:", error);
        res.status(500).json({ message: 'Error creating order', error });
    }
});
exports.createOrder = createOrder;
const getOrders = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { tableId, status, active } = req.query;
        const query = {};
        if (tableId)
            query.tableId = Number(tableId);
        if (status)
            query.status = status;
        if (active === 'true')
            query.status = { $ne: 'PAID' };
        const orders = yield Order_1.default.find(query).sort({ createdAt: -1 });
        res.json(orders);
    }
    catch (error) {
        res.status(500).json({ message: 'Error fetching orders', error });
    }
});
exports.getOrders = getOrders;
const settleTable = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { tableId } = req.params;
        const { paymentMethod, newItems, subtotal, tax, serviceCharge, total } = req.body;
        if (newItems && newItems.length > 0) {
            const closingOrder = new Order_1.default({
                tableId: Number(tableId),
                tableName: `Table ${tableId}`,
                items: newItems,
                subtotal,
                tax,
                serviceCharge,
                total,
                paymentMethod,
                status: 'PAID'
            });
            yield closingOrder.save();
        }
        yield Order_1.default.updateMany({ tableId: Number(tableId), status: { $ne: 'PAID' } }, { $set: { status: 'PAID', paymentMethod } });
        res.json({ message: 'Table settled' });
    }
    catch (error) {
        console.error("Settle error:", error);
        res.status(500).json({ message: 'Error settling table', error });
    }
});
exports.settleTable = settleTable;
// Update Order Status
const updateOrderStatus = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        const { status } = req.body;
        const updatedOrder = yield Order_1.default.findByIdAndUpdate(id, { status }, { new: true });
        res.json(updatedOrder);
    }
    catch (error) {
        res.status(500).json({ message: 'Error updating order status', error });
    }
});
exports.updateOrderStatus = updateOrderStatus;
// Get Kitchen Orders
const getKitchenOrders = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const orders = yield Order_1.default.find({ status: { $in: ['KITCHEN', 'READY', 'SERVED'] } }).sort({ createdAt: 1 });
        res.json(orders);
    }
    catch (error) {
        res.status(500).json({ message: 'Error fetching kitchen orders', error });
    }
});
exports.getKitchenOrders = getKitchenOrders;
