import { NextResponse } from "next/server";
import { ObjectId } from "mongodb";
import { getCollection } from "@/lib/mongodb";

// GET - Get a single product from ecommers collection
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    if (!id || !ObjectId.isValid(id)) {
      return NextResponse.json({ error: "Invalid product ID" }, { status: 400 });
    }

    const ecommersCollection = await getCollection<any>("ecommers");
    const product = await ecommersCollection.findOne({ _id: new ObjectId(id) });

    if (!product) {
      return NextResponse.json({ error: "Product not found" }, { status: 404 });
    }

    return NextResponse.json({
      ...product,
      _id: product._id.toString(),
    });
  } catch (error) {
    console.error("Error fetching product:", error);
    return NextResponse.json(
      {
        error: "Failed to fetch product",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 }
    );
  }
}

// PATCH - Update a product
export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    if (!id || !ObjectId.isValid(id)) {
      return NextResponse.json({ error: "Invalid product ID" }, { status: 400 });
    }

    const body = await request.json();
    const ecommersCollection = await getCollection<any>("ecommers");

    const existingProduct = await ecommersCollection.findOne({ _id: new ObjectId(id) });
    if (!existingProduct) {
      return NextResponse.json({ error: "Product not found" }, { status: 404 });
    }

    const updateData: any = {
      updatedAt: new Date().toISOString(),
    };

    if (body.title !== undefined) updateData.title = body.title;
    if (body.price !== undefined) updateData.price = parseFloat(body.price) || 0;
    if (body.cost !== undefined) updateData.cost = parseFloat(body.cost) || 0;
    if (body.stock !== undefined) updateData.stock = parseInt(body.stock) || 0;
    if (body.qty !== undefined) updateData.qty = parseInt(body.qty) || 0;
    if (body.description !== undefined) updateData.description = body.description;
    if (body.shortDescription !== undefined) updateData.shortDescription = body.shortDescription;
    if (body.fullDescription !== undefined) updateData.fullDescription = body.fullDescription;
    if (body.productDetails !== undefined) updateData.productDetails = body.productDetails;
    if (body.scat !== undefined) updateData.scat = body.scat;
    if (body.featured !== undefined) updateData.featured = body.featured;
    if (body.active !== undefined) updateData.active = body.active;
    if (body.images !== undefined) updateData.images = Array.isArray(body.images) ? body.images : [];
    if (body.thumbnails !== undefined) updateData.thumbnails = Array.isArray(body.thumbnails) ? body.thumbnails : [];
    if (body.photoUrl !== undefined) updateData.photoUrl = body.photoUrl;
    if (body.photoThumb !== undefined) updateData.photoThumb = body.photoThumb;
    if (body.variations !== undefined && Array.isArray(body.variations)) {
      updateData.variations = body.variations.map((v: any) => ({
        colorName: v.colorName,
        colorCode: v.colorCode,
        price: v.price !== undefined ? v.price : undefined,
        stock: v.stock !== undefined ? v.stock : undefined,
        images: Array.isArray(v.images) ? v.images : [],
        thumbnails: Array.isArray(v.thumbnails) ? v.thumbnails : [],
      }));
    }

    const result = await ecommersCollection.updateOne(
      { _id: new ObjectId(id) },
      { $set: updateData }
    );

    if (result.matchedCount === 0) {
      return NextResponse.json({ error: "Product not found" }, { status: 404 });
    }

    const updatedProduct = await ecommersCollection.findOne({ _id: new ObjectId(id) });

    return NextResponse.json({
      success: true,
      product: {
        ...updatedProduct,
        _id: updatedProduct._id.toString(),
      },
    });
  } catch (error) {
    console.error("Error updating product:", error);
    return NextResponse.json(
      {
        error: "Failed to update product",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 }
    );
  }
}

// DELETE - Delete a product
export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    if (!id || !ObjectId.isValid(id)) {
      return NextResponse.json({ error: "Invalid product ID" }, { status: 400 });
    }

    const ecommersCollection = await getCollection<any>("ecommers");
    const result = await ecommersCollection.deleteOne({ _id: new ObjectId(id) });

    if (result.deletedCount === 0) {
      return NextResponse.json({ error: "Product not found" }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      message: "Product deleted successfully",
    });
  } catch (error) {
    console.error("Error deleting product:", error);
    return NextResponse.json(
      {
        error: "Failed to delete product",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 }
    );
  }
}
