import { NextResponse } from "next/server";

// POST - Generate SEO metadata for a product
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { title, description, category, price, brand, images } = body;

    if (!title) {
      return NextResponse.json(
        { error: "Product title is required" },
        { status: 400 }
      );
    }

    // Generate slug from title
    const slug = title
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/(^-|-$)/g, "");

    // Generate meta title (max 60 characters)
    const metaTitle = title.length > 60 
      ? title.substring(0, 57) + "..." 
      : title;

    // Generate meta description (max 160 characters)
    let metaDescription = description || "";
    if (metaDescription.length > 160) {
      metaDescription = metaDescription.substring(0, 157) + "...";
    } else if (!metaDescription) {
      metaDescription = `Buy ${title}${category ? ` in ${category}` : ""}. ${price ? `Price: ${price}` : ""}. Fast shipping and secure checkout.`;
      if (metaDescription.length > 160) {
        metaDescription = metaDescription.substring(0, 157) + "...";
      }
    }

    // Generate keywords
    const keywords = [
      title,
      category,
      brand,
      ...(description ? description.split(" ").slice(0, 10) : []),
    ]
      .filter(Boolean)
      .join(", ");

    // Generate JSON-LD structured data
    const structuredData = {
      "@context": "https://schema.org/",
      "@type": "Product",
      name: title,
      description: description || metaDescription,
      image: images && images.length > 0 ? images : [],
      brand: brand
        ? {
            "@type": "Brand",
            name: brand,
          }
        : undefined,
      offers: {
        "@type": "Offer",
        url: `${process.env.NEXT_PUBLIC_SITE_URL || "https://yoursite.com"}/product/${slug}`,
        priceCurrency: "AED",
        price: price || "0",
        availability: "https://schema.org/InStock",
        itemCondition: "https://schema.org/NewCondition",
      },
      aggregateRating: {
        "@type": "AggregateRating",
        ratingValue: "4.5",
        reviewCount: "10",
      },
    };

    // Generate Open Graph data
    const ogTitle = title.length > 60 ? title.substring(0, 57) + "..." : title;
    const ogDescription = metaDescription;
    const ogImage = images && images.length > 0 ? images[0] : "";

    return NextResponse.json({
      success: true,
      seo: {
        metaTitle,
        metaDescription,
        metaKeywords: keywords,
        slug,
        ogTitle,
        ogDescription,
        ogImage,
        twitterCard: "summary_large_image",
        structuredData,
      },
    });
  } catch (error) {
    console.error("Error generating SEO:", error);
    return NextResponse.json(
      { error: "Failed to generate SEO metadata" },
      { status: 500 }
    );
  }
}

