// @ts-nocheck
import { Request, Response } from "express";
import asyncHandler from "../utils/asyncHandler";
import ApiError from "../utils/apiError";
import ApiResponse from "../utils/apiResponse";
import prisma from "../DB/db";
import { generateOrderNumber } from "../helpers/generateOrderNumbe"; 

export const createOrder = asyncHandler(async (req: Request, res: Response) => {
  const {id} = req.params;
  const { addressId, paymentMethod = "COD" } = req.body;

  // 1. Fetch Cart with extensive details (Product + Variant stock)
  const cart = await prisma.cart.findUnique({
    where: { userId:id },
    include: {
      items: {
        include: {
          product: {
            include:{
              variants:true,
            }
          },
          
        },
      },
    },
  });

  if (!cart || cart.items.length === 0) {
    throw new ApiError(false, 400, "Cart is empty");
  }

  let subtotal = 0;
  const orderItemsData: any[] = [];


  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 = await prisma.productVariant.findUnique({
        where: { id: item.variantId },
      });

      if (!variant) throw new ApiError(false, 404, `Variant not found for ${item.product.name}`);
      if (variant.stock < item.quantity) {
        throw new ApiError(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 = await prisma.$transaction(async (tx) => {
    // A. Create Order
    const newOrder = await tx.order.create({
      data: {
        userId,
        orderNumber: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) {
        await tx.productVariant.update({
          where: { id: item.variantId },
          data: { stock: { decrement: item.quantity } },
        });
      }
    }

    // C. Clear Cart
    await tx.cartItem.deleteMany({
      where: { cartId: cart.id },
    });

    return newOrder;
  });

  return res
    .status(201)
    .json(new ApiResponse(true, 201, "Order placed successfully", order));
});

// --- Get User Orders ---
export const getMyOrders = asyncHandler(async (req: Request, res: Response) => {
    const userId = req.user?.id;
    
    const orders = await prisma.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(true, 200, "Orders fetched", orders));
});