import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";
import { ObjectId } from "mongodb";

// POST - Generate and update SEO for a product
export async function POST(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();
    const { regenerate } = body;

    const productsCollection = await getCollection("products");
    const product = await productsCollection.findOne({
      _id: new ObjectId(id),
    });

    if (!product) {
      return NextResponse.json(
        { error: "Product not found" },
        { status: 404 }
      );
    }

    // Generate SEO using the SEO API
    const seoResponse = await fetch(
      `${process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000"}/api/seo/generate`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          title: product.title,
          description: product.description || product.shortDescription,
          category: product.scat || product.cat || product.category,
          price: product.price,
          brand: product.brand,
          images: product.images || (product.photoUrl ? [product.photoUrl] : []),
        }),
      }
    );

    const seoData = await seoResponse.json();

    if (!seoResponse.ok) {
      return NextResponse.json(
        { error: "Failed to generate SEO" },
        { status: 500 }
      );
    }

    // Update product with SEO data
    await productsCollection.updateOne(
      { _id: new ObjectId(id) },
      {
        $set: {
          seo: seoData.seo,
          updatedAt: new Date(),
        },
      }
    );

    return NextResponse.json({
      success: true,
      seo: seoData.seo,
    });
  } catch (error) {
    console.error("Error generating SEO:", error);
    return NextResponse.json(
      { error: "Failed to generate SEO" },
      { status: 500 }
    );
  }
}

