"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.getMyOrders = exports.createOrder = void 0;
const asyncHandler_1 = __importDefault(require("../utils/asyncHandler"));
const apiError_1 = __importDefault(require("../utils/apiError"));
const apiResponse_1 = __importDefault(require("../utils/apiResponse"));
const db_1 = __importDefault(require("../DB/db"));
const generateOrderNumbe_1 = require("../helpers/generateOrderNumbe");
exports.createOrder = (0, asyncHandler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { id } = req.params;
    const { addressId, paymentMethod = "COD" } = req.body;
    // 1. Fetch Cart with extensive details (Product + Variant stock)
    const cart = yield db_1.default.cart.findUnique({
        where: { userId: id },
        include: {
            items: {
                include: {
                    product: {
                        include: {
                            variants: true,
                        }
                    },
                },
            },
        },
    });
    if (!cart || cart.items.length === 0) {
        throw new apiError_1.default(false, 400, "Cart is empty");
    }
    let subtotal = 0;
    const orderItemsData = [];
    for (const item of cart.items) {
        const price = Number(item.product.price);
        subtotal += price * item.quantity;
        let variantSku = null;
        let variantSize = null;
        let variantColor = null;
        if (item.variantId) {
            const variant = yield db_1.default.productVariant.findUnique({
                where: { id: item.variantId },
            });
            if (!variant)
                throw new apiError_1.default(false, 404, `Variant not found for ${item.product.name}`);
            if (variant.stock < item.quantity) {
                throw new apiError_1.default(false, 400, `Out of stock: ${item.product.name} (${variant.size})`);
            }
            variantSku = variant.sku;
            variantSize = variant.size;
            variantColor = variant.color;
        }
        // Prepare Snapshot Data
        orderItemsData.push({
            productId: item.productId,
            variantId: item.variantId,
            productName: item.product.name,
            productImage: item.product.images[0] || "",
            sku: variantSku,
            size: variantSize,
            color: variantColor,
            price: item.product.price,
            quantity: item.quantity,
        });
    }
    const shippingCost = subtotal > 10000 ? 0 : 250;
    const tax = subtotal * 0.18;
    const total = subtotal + shippingCost + tax;
    // 3. DATABASE TRANSACTION
    const order = yield db_1.default.$transaction((tx) => __awaiter(void 0, void 0, void 0, function* () {
        // A. Create Order
        const newOrder = yield tx.order.create({
            data: {
                userId,
                orderNumber: (0, generateOrderNumbe_1.generateOrderNumber)(),
                status: "PENDING",
                isPaid: paymentMethod === "COD" ? false : true, // Logic varies
                subtotal,
                shippingCost,
                tax,
                total,
                addressId,
                items: {
                    createMany: {
                        data: orderItemsData,
                    },
                },
                payment: {
                    create: {
                        amount: total,
                        provider: paymentMethod,
                        status: paymentMethod === "COD" ? "PENDING" : "PAID"
                    }
                }
            },
        });
        // B. Decrement Stock
        for (const item of cart.items) {
            if (item.variantId) {
                yield tx.productVariant.update({
                    where: { id: item.variantId },
                    data: { stock: { decrement: item.quantity } },
                });
            }
        }
        // C. Clear Cart
        yield tx.cartItem.deleteMany({
            where: { cartId: cart.id },
        });
        return newOrder;
    }));
    return res
        .status(201)
        .json(new apiResponse_1.default(true, 201, "Order placed successfully", order));
}));
// --- Get User Orders ---
exports.getMyOrders = (0, asyncHandler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
    const orders = yield db_1.default.order.findMany({
        where: { userId },
        include: {
            items: true, // Only fetch items, not full product relation (snapshot is in items)
            payment: true
        },
        orderBy: { createdAt: 'desc' }
    });
    return res.status(200).json(new apiResponse_1.default(true, 200, "Orders fetched", orders));
}));
