import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";
import { ObjectId } from "mongodb";
import * as XLSX from "xlsx";

// Excel cell limit is 32,767 characters
const EXCEL_CELL_LIMIT = 32767;

// Helper function to truncate text to Excel's cell limit
const truncateForExcel = (text: string | null | undefined, maxLength: number = EXCEL_CELL_LIMIT): string => {
  if (!text) return "";
  const str = String(text);
  if (str.length <= maxLength) return str;
  return str.substring(0, maxLength - 3) + "...";
};

// GET - Export order as Excel
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const ordersCollection = await getCollection("orders");
    const settingsCollection = await getCollection("settings");

    // Fetch order
    const order = await ordersCollection.findOne({
      _id: new ObjectId(id),
    });

    if (!order) {
      return NextResponse.json(
        { error: "Order not found" },
        { status: 404 }
      );
    }

    // Fetch company settings
    const settings = await settingsCollection.findOne({});

    // Create workbook
    const workbook = XLSX.utils.book_new();

    // Order Summary Sheet
    const summaryData = [
      ["Order Number", truncateForExcel(order.orderNumber || String(order._id), 100)],
      ["Date", new Date(order.createdAt).toLocaleDateString()],
      ["Status", truncateForExcel(order.status, 50)],
      [""],
      ["Customer Information"],
      ["Name", truncateForExcel(order.customer?.name, 200)],
      ["Email", truncateForExcel(order.customer?.email, 200)],
      ["Phone", truncateForExcel(order.customer?.phone, 50)],
      ["Address", truncateForExcel(
        typeof order.customer?.address === "string" 
          ? order.customer.address 
          : `${order.customer?.address?.street || ""}, ${order.customer?.address?.city || ""}`,
        500
      )],
      ["City", truncateForExcel(order.customer?.address?.city, 100)],
      ["Zip", truncateForExcel(order.customer?.address?.zip, 20)],
      ["Country", truncateForExcel(order.customer?.address?.country, 100)],
      [""],
      ["Payment Information"],
      ["Method", truncateForExcel(order.payment?.method || order.paymentMethod, 50)],
      ["Status", truncateForExcel(order.payment?.status || order.paymentStatus, 50)],
      ["Transaction ID", truncateForExcel(order.payment?.transactionId, 200)],
      [""],
      ["Totals"],
      ["Subtotal", order.subtotal || order.totals?.subtotal || 0],
      ["Tax", order.tax || order.totals?.tax || 0],
      ["Shipping", order.shipping || order.totals?.shipping || 0],
      ["Discount", order.discount || order.totals?.discount || 0],
      ["Total", order.total || order.totals?.total || 0],
    ];

    const summarySheet = XLSX.utils.aoa_to_sheet(summaryData);
    XLSX.utils.book_append_sheet(workbook, summarySheet, "Order Summary");

    // Items Sheet
    const itemsData = [
      ["SKU", "Product Name", "Quantity", "Unit Price", "Total"],
      ...(order.items || []).map((item: any) => [
        truncateForExcel(item.sku, 100),
        truncateForExcel(item.name || item.title, 500),
        item.quantity || 0,
        item.price || 0,
        (item.price || 0) * (item.quantity || 0),
      ]),
    ];

    const itemsSheet = XLSX.utils.aoa_to_sheet(itemsData);
    XLSX.utils.book_append_sheet(workbook, itemsSheet, "Items");

    // Generate Excel buffer
    const excelBuffer = XLSX.write(workbook, {
      type: "buffer",
      bookType: "xlsx",
    });

    // Return Excel file
    return new NextResponse(excelBuffer, {
      headers: {
        "Content-Type":
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "Content-Disposition": `attachment; filename="order-${order.orderNumber || order._id}.xlsx"`,
      },
    });
  } catch (error) {
    console.error("Error generating Excel:", error);
    return NextResponse.json(
      { error: "Failed to generate Excel file" },
      { status: 500 }
    );
  }
}

