"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updatePaymentStatus = exports.updateOrderStatus = exports.getOrderDetails = exports.getOrders = void 0;
const client_1 = require("@prisma/client");
const prisma = new client_1.PrismaClient();
// GET /api/admin/orders
// Handles List View with Search & Tabs
const getOrders = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { search, status, tab } = req.query;
        const whereClause = {};
        // 1. Filter by Tab
        if (tab === 'pending') {
            whereClause.status = 'PENDING';
        }
        else if (tab === 'shipped') {
            whereClause.status = 'SHIPPED';
        }
        else if (tab === 'returns') {
            whereClause.status = { in: ['CANCELLED', 'RETURNED'] };
        }
        // 2. Search (Order # or Customer Name)
        if (search) {
            whereClause.OR = [
                { orderNumber: { contains: String(search), mode: 'insensitive' } },
                { user: { fullName: { contains: String(search), mode: 'insensitive' } } },
            ];
        }
        // 3. Query DB
        const orders = yield prisma.order.findMany({
            where: whereClause,
            include: {
                user: { select: { fullName: true } },
                payment: { select: { status: true } },
            },
            orderBy: { createdAt: 'desc' },
            take: 50, // Limit for performance
        });
        // 4. Format for UI
        const formattedOrders = orders.map((order) => {
            var _a, _b;
            return ({
                id: order.id,
                orderNumber: order.orderNumber,
                customer: ((_a = order.user) === null || _a === void 0 ? void 0 : _a.fullName) || 'Guest',
                date: order.createdAt.toLocaleDateString('en-IN', { month: 'short', day: 'numeric', year: 'numeric' }),
                total: Number(order.total),
                status: order.status,
                paymentStatus: ((_b = order.payment) === null || _b === void 0 ? void 0 : _b.status) || 'PENDING',
            });
        });
        res.json(formattedOrders);
    }
    catch (error) {
        console.error('Get Orders Error:', error);
        res.status(500).json({ error: 'Failed to fetch orders' });
    }
});
exports.getOrders = getOrders;
// GET /api/admin/orders/:id
// Handles the Details Page
const getOrderDetails = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c, _d, _e, _f, _g;
    try {
        const { id } = req.params;
        const order = yield prisma.order.findUnique({
            where: { id },
            include: {
                user: true,
                items: true,
                shippingAddress: true,
                payment: true,
            },
        });
        if (!order) {
            return res.status(404).json({ error: "Order not found" });
        }
        // Customer total orders count
        const customerOrderCount = order.userId
            ? yield prisma.order.count({ where: { userId: order.userId } })
            : 1;
        // Response
        const responseData = {
            id: order.orderNumber, // Display ID
            dbId: order.id, // UUID
            date: order.createdAt.toLocaleString("en-IN", {
                dateStyle: "medium",
                timeStyle: "short",
            }),
            status: order.status,
            paymentStatus: ((_a = order.payment) === null || _a === void 0 ? void 0 : _a.status) || "PENDING",
            paymentMethod: ((_b = order.payment) === null || _b === void 0 ? void 0 : _b.provider) || "N/A",
            customer: {
                name: ((_c = order.user) === null || _c === void 0 ? void 0 : _c.fullName) || "Guest",
                email: ((_d = order.user) === null || _d === void 0 ? void 0 : _d.email) ||
                    ((_e = order.shippingAddress) === null || _e === void 0 ? void 0 : _e.email) ||
                    "N/A",
                phone: ((_f = order.user) === null || _f === void 0 ? void 0 : _f.phone) ||
                    ((_g = order.shippingAddress) === null || _g === void 0 ? void 0 : _g.phone) ||
                    "N/A",
                ordersCount: customerOrderCount,
            },
            shippingAddress: order.shippingAddress,
            billingAddress: order.shippingAddress,
            // 🔥 ITEMS WITH IMAGE ADDED
            items: order.items.map((item) => ({
                name: item.productName,
                image: item.productImage, // ✅ IMAGE INCLUDED
                sku: item.sku || "N/A",
                size: item.size || null,
                color: item.color || null,
                price: Number(item.price),
                qty: item.quantity,
                total: Number(item.price) * item.quantity,
            })),
            subtotal: Number(order.subtotal),
            tax: Number(order.tax),
            shipping: Number(order.shippingCost),
            total: Number(order.total),
        };
        res.json(responseData);
    }
    catch (error) {
        console.error("Get Order Detail Error:", error);
        res.status(500).json({ error: "Failed to fetch order details" });
    }
});
exports.getOrderDetails = getOrderDetails;
// PUT /api/admin/orders/:id/status
const updateOrderStatus = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        const { status } = req.body;
        // Validate Status Enum (Optional strict check)
        // if (!Object.values(OrderStatus).includes(status)) ...
        const updatedOrder = yield prisma.order.update({
            where: { id },
            data: { status },
        });
        res.json({ message: 'Order status updated', status: updatedOrder.status });
    }
    catch (error) {
        console.error('Update Status Error:', error);
        res.status(500).json({ error: 'Failed to update status' });
    }
});
exports.updateOrderStatus = updateOrderStatus;
// PUT /api/admin/orders/:id/payment
const updatePaymentStatus = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        const { status } = req.body;
        // 1. Update Payment Record
        const updateResult = yield prisma.payment.update({
            where: { orderId: id },
            data: { status },
        });
        // 2. Sync Order.isPaid Boolean
        const isPaid = status === 'PAID';
        yield prisma.order.update({
            where: { id },
            data: { isPaid }
        });
        res.json({ message: 'Payment status updated', result: updateResult });
    }
    catch (error) {
        console.error('Update Payment Error:', error);
        res.status(500).json({ error: 'Failed to update payment status' });
    }
});
exports.updatePaymentStatus = updatePaymentStatus;
