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

// POST — report a post (members only; admins see reports in circle detail)
export async function POST(
  req: Request,
  { params }: { params: Promise<{ id: string; postId: string }> }
) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const { postId } = await params;

  const membership = await sql.unsafe(
    `SELECT 1 FROM circle_posts p
     JOIN circle_members cm ON cm.circle_id = p.circle_id AND cm.family_id = $2
     WHERE p.id = $1`,
    [postId, familyId]
  );
  if (!membership.length) return NextResponse.json({ error: "Not a member" }, { status: 403 });

  const { reason } = await req.json();

  await sql.unsafe(
    `INSERT INTO post_reports (post_id, reported_by, reason) VALUES ($1, $2, $3)
     ON CONFLICT DO NOTHING`,
    [postId, familyId, reason ?? null]
  );

  return NextResponse.json({ success: true });
}
