import { NextResponse } from "next/server";
import { ObjectId } from "mongodb";
import { getCollection } from "@/lib/mongodb";

// GET - Get a single product
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 productsCollection = await getCollection<any>("products");
    const product = await productsCollection.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 productsCollection = await getCollection<any>("products");

    const existingProduct = await productsCollection.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.price !== undefined) updateData.price = parseFloat(body.price) || 0;
    if (body.cost !== undefined) updateData.cost = parseFloat(body.cost) || 0;
    if (body.newCost !== undefined) updateData.newCost = parseFloat(body.newCost) || 0;
    if (body.lastSell !== undefined) updateData.lastSell = parseFloat(body.lastSell) || 0;
    if (body.supplier !== undefined) updateData.supplier = body.supplier || "";
    if (body.stock !== undefined) updateData.stock = parseInt(body.stock) || 0;
    if (body.rack !== undefined) updateData.rack = body.rack || "";
    if (body.qty !== undefined) updateData.qty = parseInt(body.qty) || 0;
    if (body.category !== undefined) {
      updateData.scat = body.category || "";
      updateData.cat = body.category || "";
      updateData.category = body.category || "";
    }
    if (body.itc1 !== undefined) updateData.itc1 = body.itc1 || "";
    if (body.itn !== undefined) updateData.itn = body.itn || "";
    if (body.active !== undefined) updateData.active = body.active;

    const result = await productsCollection.updateOne(
      { _id: new ObjectId(id) },
      { $set: updateData }
    );

    if (result.matchedCount === 0) {
      return NextResponse.json({ error: "Product not found" }, { status: 404 });
    }

    // Track price changes
    if (body.updatePrice && body.price !== undefined && body.price !== existingProduct.price) {
      const pricesCollection = await getCollection<any>("prices");
      await pricesCollection.insertOne({
        barcode: existingProduct.bcode1 || existingProduct.sku || id,
        productId: id,
        price: updateData.price,
        previousPrice: existingProduct.price || 0,
        updatedAt: new Date().toISOString(),
        createdAt: new Date().toISOString(),
      });
    }

    // Track stock changes
    if (body.updateStock && (body.stock !== undefined || body.qty !== undefined)) {
      const stockUpdatesCollection = await getCollection<any>("stock_updates");
      await stockUpdatesCollection.insertOne({
        barcode: existingProduct.bcode1 || existingProduct.sku || id,
        productId: id,
        stock: updateData.stock !== undefined ? updateData.stock : existingProduct.stock || 0,
        qty: updateData.qty !== undefined ? updateData.qty : existingProduct.qty || 0,
        previousStock: existingProduct.stock || 0,
        previousQty: existingProduct.qty || 0,
        rack: updateData.rack || existingProduct.rack || "",
        updatedAt: new Date().toISOString(),
        createdAt: new Date().toISOString(),
      });
    }

    const updatedProduct = await productsCollection.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 productsCollection = await getCollection<any>("products");
    const result = await productsCollection.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 }
    );
  }
}
