import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";

// POST - Create a new product in ecommers collection
export async function POST(request: Request) {
  try {
    const body = await request.json();

    // Validate required fields
    if (!body.title || !body.sku) {
      return NextResponse.json(
        { error: "Title and SKU are required" },
        { status: 400 }
      );
    }

    // Get ecommers collection
    const ecommersCollection = await getCollection<any>("ecommers");

    // Check if SKU already exists
    const existingProduct = await ecommersCollection.findOne({ sku: body.sku });
    if (existingProduct) {
      return NextResponse.json(
        { error: "Product with this SKU already exists" },
        { status: 400 }
      );
    }

    // Prepare product data
    const productData = {
      title: body.title || "",
      itc1: body.itc1 || "",
      itn: body.itn || "",
      sku: body.sku || "",
      bcode1: body.bcode1 || "",
      description: body.description || "",
      shortDescription: body.shortDescription || "",
      fullDescription: body.fullDescription || "",
      productDetails: body.productDetails || "",
      qty: typeof body.qty === "number" ? body.qty : parseFloat(body.qty) || 0,
      stock: typeof body.stock === "number" ? body.stock : parseFloat(body.stock) || 0,
      cost: typeof body.cost === "number" ? body.cost : parseFloat(body.cost) || 0,
      price: typeof body.price === "number" ? body.price : parseFloat(body.price) || 0,
      supplier: body.supplier || "",
      rack: body.rack || "",
      lastSell: typeof body.lastSell === "number" ? body.lastSell : parseFloat(body.lastSell) || 0,
      newCost: typeof body.newCost === "number" ? body.newCost : parseFloat(body.newCost) || 0,
      category: body.category || "",
      scat: body.scat || "",
      cat: body.cat || "",
      itc: body.itc || "",
      featured: body.featured !== undefined ? body.featured : false,
      mfg: body.mfg || "",
      vat: typeof body.vat === "number" ? body.vat : parseFloat(body.vat) || 0,
      unit: body.unit || "",
      // Images
      images: Array.isArray(body.images) ? body.images : [],
      thumbnails: Array.isArray(body.thumbnails) ? body.thumbnails : [],
      photoUrl: body.photoUrl || (Array.isArray(body.images) && body.images.length > 0 ? body.images[0] : ""),
      photoThumb: body.photoThumb || (Array.isArray(body.thumbnails) && body.thumbnails.length > 0 ? body.thumbnails[0] : ""),
      // Variations with thumbnails
      variations: Array.isArray(body.variations)
        ? body.variations.map((v: any) => ({
            colorName: v.colorName,
            colorCode: v.colorCode,
            price: v.price,
            stock: v.stock,
            images: Array.isArray(v.images) ? v.images : [],
            thumbnails: Array.isArray(v.thumbnails) ? v.thumbnails : [],
          }))
        : [],
      // Metadata
      active: body.active !== undefined ? body.active : true,
      createdAt: body.createdAt || new Date().toISOString(),
      updatedAt: body.updatedAt || new Date().toISOString(),
    };

    // Insert product into ecommers collection
    const result = await ecommersCollection.insertOne(productData);

    if (!result.acknowledged) {
      throw new Error("Failed to insert product");
    }

    return NextResponse.json(
      {
        success: true,
        message: "Product created successfully",
        productId: result.insertedId.toString(),
        product: {
          ...productData,
          _id: result.insertedId.toString(),
        },
      },
      { status: 201 }
    );
  } catch (error) {
    console.error("Error creating product:", error);
    
    // Provide more detailed error messages
    const errorMessage = error instanceof Error ? error.message : "Unknown error";
    let userMessage = "Failed to create product";
    let statusCode = 500;
    
    // Check for MongoDB connection errors
    if (errorMessage.includes("SSL") || errorMessage.includes("TLS") || errorMessage.includes("alert")) {
      userMessage = "MongoDB connection failed: Your IP address is not whitelisted in MongoDB Atlas. Please whitelist your IP in MongoDB Atlas Network Access.";
      statusCode = 503; // Service Unavailable
    } else if (errorMessage.includes("ECONNREFUSED") || errorMessage.includes("timeout")) {
      userMessage = "MongoDB connection failed: Cannot connect to MongoDB Atlas. Please check your connection and MongoDB Atlas cluster status.";
      statusCode = 503;
    } else if (errorMessage.includes("Authentication failed") || errorMessage.includes("bad auth")) {
      userMessage = "MongoDB authentication failed: Please check your MongoDB credentials.";
      statusCode = 401;
    } else if (errorMessage.includes("MONGODB_URI")) {
      userMessage = "MongoDB configuration error: MONGODB_URI environment variable is not set or invalid.";
      statusCode = 500;
    }
    
    return NextResponse.json(
      {
        error: userMessage,
        details: errorMessage,
        type: "database_error",
      },
      { status: statusCode }
    );
  }
}

// GET - Fetch all products from ecommers collection
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const search = searchParams.get("search") || "";
    const page = parseInt(searchParams.get("page") || "1", 10);
    const requestedLimit = parseInt(searchParams.get("limit") || "50", 10);
    const limit = Math.min(Math.max(requestedLimit, 1), 1000);
    const skip = (page - 1) * limit;

    const ecommersCollection = await getCollection<any>("ecommers");

    // Build search query
    const query: any = {};
    if (search.trim()) {
      const escapedSearch = search.trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
      query.$or = [
        { title: { $regex: escapedSearch, $options: "i" } },
        { sku: { $regex: escapedSearch, $options: "i" } },
        { bcode1: { $regex: escapedSearch, $options: "i" } },
        { description: { $regex: escapedSearch, $options: "i" } },
        { shortDescription: { $regex: escapedSearch, $options: "i" } },
        { fullDescription: { $regex: escapedSearch, $options: "i" } },
        { productDetails: { $regex: escapedSearch, $options: "i" } },
        { scat: { $regex: escapedSearch, $options: "i" } },
        { cat: { $regex: escapedSearch, $options: "i" } },
        { itc1: { $regex: escapedSearch, $options: "i" } },
        { itn: { $regex: escapedSearch, $options: "i" } },
        { itc: { $regex: escapedSearch, $options: "i" } },
        { category: { $regex: escapedSearch, $options: "i" } },
        { supplier: { $regex: escapedSearch, $options: "i" } },
        { mfg: { $regex: escapedSearch, $options: "i" } },
      ];
    }

    // Only fetch active products by default
    query.active = { $ne: false };

    const [products, total] = await Promise.all([
      ecommersCollection
        .find(query)
        .sort({ createdAt: -1 }) // Sort by newest first
        .skip(skip)
        .limit(limit)
        .toArray(),
      ecommersCollection.countDocuments(query),
    ]);

    return NextResponse.json({
      products: products.map((p: any) => ({
        ...p,
        _id: p._id?.toString() || p._id,
      })),
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error("Error fetching products:", error);
    return NextResponse.json(
      {
        error: "Failed to fetch products",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 }
    );
  }
}

