import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily } from "@/lib/auth";

export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });
  const userId = auth.session!.userId!;
  const { id } = await params;

  const updates = await request.json();

  // verify ownership
  const check = await sql`
    SELECT rp.id FROM recommended_products rp
    JOIN member_profiles mp ON mp.id = rp.profile_id
    WHERE rp.id = ${id} AND mp.user_id = ${userId}
  `;
  if (!check[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });

  if ("title" in updates) await sql`UPDATE recommended_products SET title = ${updates.title} WHERE id = ${id}`;
  if ("description" in updates) await sql`UPDATE recommended_products SET description = ${updates.description} WHERE id = ${id}`;
  if ("url" in updates) await sql`UPDATE recommended_products SET url = ${updates.url} WHERE id = ${id}`;
  if ("image_url" in updates) await sql`UPDATE recommended_products SET image_url = ${updates.image_url} WHERE id = ${id}`;
  if ("category" in updates) await sql`UPDATE recommended_products SET category = ${updates.category} WHERE id = ${id}`;
  if ("display_order" in updates) await sql`UPDATE recommended_products SET display_order = ${updates.display_order} WHERE id = ${id}`;
  if ("is_active" in updates) await sql`UPDATE recommended_products SET is_active = ${updates.is_active} WHERE id = ${id}`;

  const rows = await sql`SELECT * FROM recommended_products WHERE id = ${id}`;
  return NextResponse.json({ product: rows[0] });
}

export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });
  const userId = auth.session!.userId!;
  const { id } = await params;

  const check = await sql`
    SELECT rp.id FROM recommended_products rp
    JOIN member_profiles mp ON mp.id = rp.profile_id
    WHERE rp.id = ${id} AND mp.user_id = ${userId}
  `;
  if (!check[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await sql`DELETE FROM recommended_products WHERE id = ${id}`;
  return NextResponse.json({ success: true });
}
